using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Microsoft.VisualBasic;
using System.Threading;
using System.Runtime.InteropServices;
using CommLayer;
using Tamir.IPLib;
using Tamir.IPLib.Packets;
using System.Net.NetworkInformation;
using System.Diagnostics;


using QTOControlLib;
using QTOLibrary;
using ImageFileOverlay;
using VideoCapture;
using DirectShowLib;
using ImageFast;
using FileBrowser;
using ShellDll;
using DoublePixel;
using Distribution;
using Magnolia;


using XYThreadPoolLib;

//Struct for Image Ingestion Processes 
struct Media
{
    public int mediaID;
    public int sliceIndex;
    public string sourceFolder;
}


namespace AssetCapture
{
    public partial class Form1 : Form
    {
        string m_VideoStorePath; //Set by the Database value in GlobalConfig Table //Provider=SQLOLEDB.1;Password=sa;Persist Security Info=True;User ID=sa;Initial Catalog=SuperSignTest;Data Source=SQL01
        //string m_ConnectionString = @"Data Source=STDEVELOPMENT\SHOWANDTELL;Initial Catalog=SuperSign;Persist Security Info=True;User ID=sa ; Password=magnolia2";
        string m_ConnectionString = @"Data Source=SQL01;Initial Catalog=SuperSign;Persist Security Info=True;User ID=sa ; Password=sa";

        //string m_ConnectionString = @"Data Source=SQL01;Initial Catalog=SuperSignAssetCapture;Persist Security Info=True;User ID=sa ; Password=sa";
        string m_UseExistAssetName;
        string m_errMsg = "";
        int m_UseExistAssetID;
        int m_ExistAssetChannelID;
        int m_TotalSlices; //Total Slices of Media need to be process
        int m_CurrentPlayerIndex; 
        int m_FrameHight; //The frame size of Player
        int m_FrameWidth; 
        int m_BCD; //The TimeCode for Deck Player
        int m_StartFrame; //The StartFrame for the Deck Capture
        int m_EndFrame;
        int m_Transdegree;
        int m_TotalFrames; //Set by the Call back function in the Video Intestion 
        int m_Percentage = 0;
        int m_counterFlag = 0;
        int m_Left_STW, m_Left_STH, m_Left_LW, m_Left_LH;
        int m_Right_STW, m_Right_STH, m_Right_LW, m_Right_LH;
        int m_RectHight , m_RectWidth, m_RectHStart, m_RectWStart;
        int m_Display;
        int m_Quality;
        int m_OutputFormat;
        int m_UserID;
        bool m_ForceNotInterlace = false;
        bool m_TwoRibbonStrech = true;
        bool m_SameSize;
        bool m_Capturing = false; //offset to determine if the application is capturing 
        bool m_Ingesting = false;//offset to determine if the application is ingesting
        bool m_DeckFinding = false; //offset to determine if the application is searching on the deck
        bool m_ErrorOccurred = false;
        bool m_Overlayflag = false; //offset if the overlay image is appied 
        bool m_IngestionComplete = false;
        bool m_MainTComplete = false; //offset for Displaying the video ingestion process
        bool m_FileCountOffset = false;
        bool m_Interlacing;
        bool m_PauseByUser = false;
        bool m_LiveCapture = false;
        bool m_DeckJumping = false;
        bool m_ExtractComplete = false;
        bool m_IngestFromFolder = false;
        bool m_ImageSlide = false;
        bool m_Stopping = true;
        bool m_MitsuDoubleFrame = false;
        object m_DeviceOB; //the DirectShow Object for Capture Card
        DsDevice m_Dvc = null; //the DS object for Deck
        IAMExtTransport m_ExtTransport = null; //The interface for DS object to perform deck control
        IAMTimecodeReader m_TimeReader = null; //The interface for DS object to extract time code
        Image m_OverlayImage;
        IntPtr m_ip = IntPtr.Zero; //pointer for image Capture
        OpenFileDialog m_OpenFileDialog1 = new OpenFileDialog();
        FolderBrowserDialog m_FolderBrowserDialog1 = new FolderBrowserDialog();
        VideoCapture.VideoCapture m_VidOb = new VideoCapture.VideoCapture();
        Distribution.Distribution m_Go = new Distribution.Distribution();
        ImageCapture.Capture m_CamOb = null;
        AssetFunction m_assetFtOb = new AssetFunction();
        ImageIngestion m_imageingestOb = new ImageIngestion();
        FrameCalculate m_FrameCal = new FrameCalculate();
        VideoIngestion m_vIob = new VideoIngestion();
        AssetLoginForm aLFrom;
            
        delegate void imageCut(object Ob);


        //For Display the Property page of Capture Card
        [DllImport("olepro32.dll")]
        public static extern int OleCreatePropertyFrame(
            IntPtr hwndOwner,
            int x,
            int y,
            [MarshalAs(UnmanagedType.LPWStr)] string lpszCaption,
            int cObjects,
            [MarshalAs(UnmanagedType.Interface, ArraySubType = UnmanagedType.IUnknown)] 
			ref object ppUnk,
            int cPages,
            IntPtr lpPageClsID,
            int lcid,
            int dwReserved,
            IntPtr lpvReserved);

        /// <summary>
        /// Startup Immediately,
        /// Initialize Capture Card, create the device object.
        /// Start the Timer to update the TimeCode from the deck
        /// Initialze some important class memeber
        /// Trigger the Distribution Event
        /// Start the Non-Normolize Database Maintaining
        /// </summary>
        public Form1()
        {
            InitializeComponent();
            m_assetFtOb.TCPIni();
            m_vIob.VideoInitialize();
            sRWDeckToolStripMenuItem.Checked = true;
            m_imageingestOb.EncoderInit();
            AssetLoginForm.UserLogin report = new AssetLoginForm.UserLogin(ReportUserID); //Delegate call back function 
            aLFrom = new AssetLoginForm(m_ConnectionString,  report);
            this.AddOwnedForm(aLFrom);
            try
            {
                //Find Decklink Video Capture Card and initialize the device
                foreach (DsDevice device in DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice))
                {
                    if (device.Name == "Decklink Video Capture")
                    {
                        m_Dvc = device;
                        break;
                    }
                }
                Guid iid = typeof(IBaseFilter).GUID;
                m_Dvc.Mon.BindToObject(null, null, ref iid, out m_DeviceOB);
                m_ExtTransport = (IAMExtTransport)m_DeviceOB;
                m_TimeReader = (IAMTimecodeReader)m_DeviceOB;
            }
            catch (Exception err)
            {
                MessageBox.Show("The Capture Card is Broken/Not Installed \n" + err);
            }

            finally
            {
                timer1.Start(); //Timer start 
                timer1.Tick += new EventHandler(timer1_Tick);

                timer2.Start();
                timer2.Tick += new EventHandler(timer2_Tick);

                timer3.Start();
                timer3.Tick += new EventHandler(timer3_Tick);

                string getVideoStorePath = "sproc_ATC_Sel_VideoStorePath"; //Call stored procedure for retrieving the videostoredpath from GlobalConfig Table

                m_VideoStorePath = getDataObject(getVideoStorePath).ToString();

                startToolStripMenuItem_Click(this.startToolStripMenuItem, null); // Start the Distribtion Function

                ThreadPool.QueueUserWorkItem(new WaitCallback(CheckIdle));

                ThreadPool.QueueUserWorkItem(new WaitCallback(NNMaster)); //Start new thread for running Non-Normolize Database Maintain 
            }

            checkAutoProcess();

            Logout();
        }

        private void Logout()
        {
            if (m_CamOb != null)
                m_CamOb.Dispose();
            this.Enabled = false;
            string command = "Update Globalconfig set Value = 'false' where Property = 'AssetUserLogin'";
            UpdateDataBase(command);
            m_UserID = 0;
            TriggerLoginForm();
        }

        private void TriggerLoginForm()
        {
            picPreviewBox.Image = null;
            aLFrom.Show();
        }

        private void ReportUserID(int id)
        {
            m_UserID = id;
            string command = "Update Globalconfig set Value = 'true' where Property = 'AssetUserLogin'";
            UpdateDataBase(command);

            command = "select value from GlobalConfig where Property = 'FTPBatchStopping'";
            bool stopping = Convert.ToBoolean(getDataObject(command));

            if (stopping)
            {
                WaitingForm waitForm = new WaitingForm(m_ConnectionString,WaitEnableForm);
                this.AddOwnedForm(waitForm);
                waitForm.Show();
            }
            else
                this.Enabled = true;
        }

        private void WaitEnableForm()
        {
            m_Stopping = false;
        }

        private void checkAutoProcess()
        {
            //string command1;
            //string command2;

            //command1 = "select value from GlobalConfig where Property = 'FTPBatchIngestIdle'";
            //command2 = "select value from GlobalConfig where Property = 'AssetThumbnailIdle'";

            //bool FTPIdle = Convert.ToBoolean(getDataObject(command1));
            //bool ThumbIdle = Convert.ToBoolean(getDataObject(command2));

            //if (FTPIdle && ThumbIdle)
                m_assetFtOb.autoProcess();
        }

        void timer3_Tick(object sender, EventArgs e)
        {

            if (DateTime.Now.Hour == 3)
            {
                try
                {
                    checkAutoProcess();

                    if (!m_Ingesting && !m_DeckFinding && !m_Capturing && !m_DeckJumping)
                    {
                        if (this.Enabled)
                        {
                            Logout();
                        }
                        //else if (!startToolStripMenuItem.Enabled)
                        //{
                        //    StopDistribution();
                        //    Thread.Sleep(20000);
                        //    startDistribution();
                        //}
                    }
                }
                catch (Exception err)
                {
                }
            }
        }

        /// <summary>
        /// Time Ticking Event
        /// Timmer2 running at 100ms interval to constantly update the status of connection to the remote deck
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void timer2_Tick(object sender, EventArgs e)
        {
            if (m_assetFtOb.m_DeckResponse == "" || m_assetFtOb.m_DeckResponse == "Failure")
            {
                deckSignal.Image = AssetCapture.Properties.Resources.red;
            }
            else if (m_assetFtOb.m_DeckResponse == "yellow")
            {
                deckSignal.Image = AssetCapture.Properties.Resources.yellow;
            }
            else
            {
                deckSignal.Image = AssetCapture.Properties.Resources.green;
            }
            if (m_assetFtOb.Copying)
            {
                if (progressBar3.Value < 100)
                    progressBar3.Increment(10);
                else
                    progressBar3.Value = 0;

                Btn_CreateBatch.Enabled = false;
            }
            else
            {
                progressBar3.Value = 0;
                Btn_CreateBatch.Enabled = true;
            }

            if (!m_Stopping)
            {
                this.Enabled = true;
                m_Stopping = true;
            }
        }
        
        /// <summary>
        /// Call the NN_Master Stored Procedure to update the Database
        /// Start from the beginning of Application 
        /// </summary>
        /// <param name="dumpOb"></param>
        private void NNMaster(object dumpOb)
        {
            bool UpdateFlag = false;

            if ((DateTime.Now.Minute > 0 && DateTime.Now.Minute < 2) || (DateTime.Now.Minute > 30 && DateTime.Now.Minute < 32))
            {
                string command = "dbo.sproc_NN_Master";
                if(!UpdateFlag)
                    UpdateDataBase(command);

                UpdateFlag = true;
            }
            else
                UpdateFlag = false;

            Thread.Sleep(2000);

            ThreadPool.QueueUserWorkItem(new WaitCallback(NNMaster));
        }

        /// <summary>
        /// Reset the device to be displayed as Live mode or Deck mode
        /// The videoPreviewTab Tab changing event will call the device Reset
        /// </summary>
        /// <param name="panelChosen">The control panel that is going to be displayed on</param>
        private void deviceReset()
        {
            if (m_CamOb != null)
                m_CamOb.Dispose();
            m_CamOb = new ImageCapture.Capture(m_Dvc, deckPanel);
        }

        /// <summary>
        /// Perform those Check at interval of 10ms to make sure all the value display on the application is uptodate
        /// Timer1 event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void timer1_Tick(object sender, EventArgs e)
        {
            Thread.CurrentThread.Priority = ThreadPriority.AboveNormal;

            if(m_TimeReader != null)
                UpdateTimeCode();

            if (sender == timer1)
            {             
                //Change the Text of button based on the requirement 
                if (m_Capturing)
                {
                    captureSourceToNewFrameInFolder.Text = "Capturing !! \n Click Here To Stop Capturing";
                    captureSourceToNewFrameInFolder.ForeColor = System.Drawing.Color.Red;
                }
                else if (!m_Capturing && m_DeckFinding)
                {
                    captureSourceToNewFrameInFolder.ForeColor = System.Drawing.Color.Red;
                    captureSourceToNewFrameInFolder.Text = "Searching !!\n Click Here To Stop Searching";
                }
                else if (!m_Capturing)
                {
                    captureSourceToNewFrameInFolder.ForeColor = System.Drawing.Color.Black;
                    captureSourceToNewFrameInFolder.Text = "Capture Source \n to New Frame Sequence in Folder";
                }

                if (m_DeckFinding)
                {
                    jumpTo.Text = "Stop!";
                    jumpTo.ForeColor = System.Drawing.Color.Red;
                }
                else
                {
                    jumpTo.Text = "Jump";
                    jumpTo.ForeColor = System.Drawing.Color.Black;
                }

                //if the application is doing image processing and main thread had not finish video ingestion 
                if (m_Percentage != 0 && !m_MainTComplete)
                {
                    displayProgress();
                }

            }
        }

        /// <summary>
        /// Retrieve the lastest timecode from the Deck and display on the Form.
        /// Call by the Timer1
        /// Get Called Every 10 ms
        /// </summary>
        private void UpdateTimeCode()
        {
            int timecode;
            string timeText = m_VidOb.TimeBarDisplay(m_TimeReader, out timecode); //Read the Time display on the Deck
            deckLabel.Text = "Deck " + timeText;
            imageDeckTime.Text = "Deck " + timeText;
            Label_DeckTime2.Text = "Deck " + timeText;
            m_BCD = timecode; //Set the timecode to Gobal value
        }

        /// <summary>
        /// Initialize the Exisiting Asset List
        /// When Form is loadup 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            inistialExistingList();
        }


        //Deck Search function for image capture
        private void jumpTo_Click(object sender, EventArgs e)
        {
            if (!m_DeckFinding)
            {
                ConvertToBCD(2);

                ThreadStart ts = new ThreadStart(JumpDeck);
                Thread t = new Thread(ts);
                t.Start();
            }
            else
            {
                m_DeckFinding = false;
                m_ExtTransport.put_Mode(ExtTransportModes.Stop);
            }
        }

        private void JumpDeck()
        {
            m_DeckJumping = true;
            LocatedDeck();
            m_DeckFinding = false;
            m_DeckJumping = false;
            m_PauseByUser = false;
            m_Go.threadSleepCount = 0;
        }

        /// <summary>
        /// Figure out if the click is for Live Capture or Deck Capture 
        /// Click Event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void captureSourceToNewFrameInFolder_Click(object sender, EventArgs e)
        {
            //if the Image Capture object is existed , dispose it 
            if (m_CamOb != null) 
                m_CamOb.Dispose();
            string savingPath;

            //Retrieve the selected path in the file exploer with givin video name
            //Save as AVI format video
            if (Directory.Exists(browser1.itemPath))
                savingPath = browser1.itemPath + "\\" + sequenceName.Text + ".avi";
            else if(Directory.Exists(browser1.SelectedItem.Path))
                savingPath = browser1.SelectedItem.Path + "\\" + sequenceName.Text + ".avi";
            else
            {
                displayError("Please Selected a Valided Folder!");
                return;
            }

            if (!m_Capturing && !m_DeckFinding)
            {
                m_VidOb.InitialVideo(savingPath, deckPanel);
                ConvertToBCD(1);

                //Start one Single thread to ensure no delay on the capture process
                ThreadStart ts = new ThreadStart(Record);
                Thread t = new Thread(ts);
                t.Start();
            }
            else
            {
                StopRecord();
            }
        }


        /// <summary>
        /// To locate the reqired poistion on the deck 
        /// Call by Capture click Event, Image Jump function
        /// *** The Deck delay offset value is a bit tricky, may be different for different deck
        /// *** The unknow delay which result the timecode update delay and locat the deck at wrong time poistion
        /// *** Seems most delay likely to happen at 00:10:00/00 for unknown reason
        /// *** More test needed for different behavior of Deck Tape
        /// </summary>
        private void LocatedDeck()
        {
            m_DeckFinding = true;
            m_PauseByUser = true;
            m_Go.Pause();
            while (m_Go.threadSleepCount < 4)
                Thread.Sleep(100);
            //Thread.CurrentThread.Priority = ThreadPriority.Highest;

            if (m_CamOb != null)
                m_CamOb.Dispose();

            int deckOneOffsetA;
            int deckOneOffsetB;

            

            if (m_DeckJumping)
            {
                deckOneOffsetA = 500;
                deckOneOffsetB = 15;
            }
            else
            {
                deckOneOffsetA = 2000;
                deckOneOffsetB = 2;
            }

                int targetFrame = m_StartFrame - deckOneOffsetA; //Offset for deck's delay responds

                if (m_BCD >= m_StartFrame)
                {
                    //Deck renew 
                    m_ExtTransport.put_Mode(ExtTransportModes.Rew);

                    //Renew until the loop break
                    while (1180000000 > m_BCD && m_BCD > targetFrame)
                    {
                        AntiFreez();
                    }
                    //Deck STop
                    m_ExtTransport.put_Mode(ExtTransportModes.Stop);
                }
                else if (m_BCD < m_StartFrame)
                {
                    //Deck FastForward
                    m_ExtTransport.put_Mode(ExtTransportModes.FF);
                    while (m_BCD < targetFrame)
                    {
                        AntiFreez();
                    }
                    m_ExtTransport.put_Mode(ExtTransportModes.Stop);
                }


                targetFrame = m_StartFrame - deckOneOffsetB;

                //Deck Play
                m_ExtTransport.put_Mode(ExtTransportModes.Play);

                if (targetFrame < m_BCD)
                {
                    m_ExtTransport.put_Mode(ExtTransportModes.Stop);
                    LocatedDeck();
                }

                while (m_BCD < targetFrame)
                {
                    AntiFreez();
                }

                if (m_DeckJumping)
                {
                    m_ExtTransport.put_Mode(ExtTransportModes.Freeze);
                    //Console.WriteLine("TargetFrame:" + targetFrame);
                    //Console.WriteLine("BCD:" + m_BCD);
                    ////UpdateBCDCode();
                    //if ((m_BCD - m_StartFrame) > 5)
                    //    LocatedDeck();
                    //Thread.Sleep(500);
                }

                if ((m_BCD - m_StartFrame) > 5)
                    LocatedDeck();
                
        }

        /// <summary>
        /// The function is existed to prevent the program halt when Deck reach the very begining or end of tape
        /// Call by locatedDeck
        /// It is called when the deck is searching
        /// </summary>
        private void AntiFreez()
        {
            //if the deck searching is abort
            if(!m_DeckFinding)
                Thread.CurrentThread.Abort();

            //Copy the lastest BCD, if the BCD is being the same for a while, then stop searching
            if (Math.Abs(m_BCD - m_counterFlag) > 500)
                m_counterFlag = m_BCD;
        }

        /// <summary>
        /// Start to Capture the video from the capture card, automatically trace to the start time of video and finish at end time
        /// Start Record into the RAID hard drive
        /// Call by capture click event
        /// Call when the button click
        /// </summary>
        private void Record()
        {
            if (!m_LiveCapture)
            {
                if ((m_EndFrame - m_StartFrame) > 0)
                    LocatedDeck(); //Start Searching

                //m_ExtTransport.put_Mode(ExtTransportModes.Rew);
                //Thread.CurrentThread.Join(500);
                //m_ExtTransport.put_Mode(ExtTransportModes.Play);

                m_Capturing = true;


                if (m_BCD < m_EndFrame) //|| startFrame == endFrame) //don't know why i implement this line
                {
                    m_VidOb.Capture();
                }

                int localEndFrame = m_EndFrame + 5;

                while (m_BCD < localEndFrame)
                {
                    if (m_Capturing == false)
                    {
                        StopRecord();
                        Thread.CurrentThread.Abort();
                    }
                    AntiFreez();
                }
                StopRecord();
            }
            else
            {
                m_Capturing = true;      
                m_VidOb.Capture();
            }
            
        }

        /// <summary>
        /// Stop Recording
        /// Call by Record function 
        /// When the Stop Capture buttn Click
        /// </summary>
        private void StopRecord()
        {
            m_DeckFinding = false;
            m_VidOb.Stop();
            if(m_LiveCapture) //if it is liveCapturing, reset the device object
                deviceReset();
            m_ExtTransport.put_Mode(ExtTransportModes.Stop);
            m_Capturing = false;
            m_PauseByUser = false;
            m_Go.threadSleepCount = 0;
        }

        /// <summary>
        /// Convert the real time into TimeCode,
        /// Call by the Record function 
        /// Right before recording start
        /// </summary>
        /// <param name="index"></param>
        private void ConvertToBCD(int index)
        {
            if (index == 1) //TimeCode required for video Ingestion
            {
                m_StartFrame = m_VidOb.FrameCountToBCD(Convert.ToInt32(startHour.Text), Convert.ToInt32(startMin.Text), Convert.ToInt32(startSec.Text), Convert.ToInt32(startFrame.Text));
                m_EndFrame = m_VidOb.FrameCountToBCD(Convert.ToInt32(endHour.Text), Convert.ToInt32(endMin.Text), Convert.ToInt32(endSec.Text), Convert.ToInt32(endFrame.Text));
            }
            else //Time Code required for Image Capturing
            {
                m_StartFrame = m_VidOb.FrameCountToBCD(Convert.ToInt32(imageHour.Text), Convert.ToInt32(imageMin.Text), Convert.ToInt32(imageSec.Text), Convert.ToInt32(imageFrame.Text));
            }
        }


        /// <summary>
        /// will Set the m_ErrorOccurred to true and stop all the activity
        /// This is been used for call back function for other module library
        /// </summary>
        /// <param name="errMessage"></param>
        public void displayError(string errMessage)
        {
            //MessageBox.Show(errMessage);
            m_ErrorOccurred = true;
            //Reset both Progress Bar in the case of error occur before
        }

        public void downQuality(int down)
        {
            m_Quality = down;
        }

        /// <summary>
        /// Check if the input is valid and give proper error message before ingestion process
        /// When the create Asset button Click
        /// </summary>
        private void CheckInput()
        {
            int result;
            string overlayPath;
            string transparent;

            m_ErrorOccurred = false;
            if (MediaIngestion.SelectedIndex == 0)
            {
                if (!Information.IsNumeric(TBX_DMin.Text) || !Information.IsNumeric(TBX_DSec.Text))
                    m_errMsg += "Please enter valided number for duration";
                else if ((Convert.ToInt32(TBX_DMin.Text) * 60 + Convert.ToInt32(TBX_DSec.Text)) < 3)
                    m_errMsg += "Duration must be more than 3 sec";

                //Check for duplicated Asset Name
                string command = "sproc_ATC_Sel_Asset_Name_Duplicated @AssetName ='" + newAssetName.Text + "'"; 
                result = Convert.ToInt32(getDataObject(command));
                if (result != -1)
                    m_errMsg += "The System already contains an Asset with this name. Plase choose a unique Asset name \n";
                
                //Check for other errors
                if (channelID.SelectedIndex == 0)
                    m_errMsg +="Please Choose a Channel for Asset to Play \n";
                if (IngestedFromPath.Text == "Ingested From Path" ||IngestedFromPath.Text == "" )
                    m_errMsg += "Please Choose a Source to be Ingested into an Asset \n";
                if(!File.Exists(IngestedFromPath.Text)&&!Directory.Exists(IngestedFromPath.Text))
                    m_errMsg += "The File/Directory is not exist! Please Check the address !";
                
                overlayPath = assetImageOverlayPath.Text;
                transparent = transparentDegree.Text;
            }
            else
            {
                if (!Information.IsNumeric(TBX_DMin2.Text) || !Information.IsNumeric(TBX_DSec2.Text))
                    m_errMsg += "Please enter valided number for duration";
                else if ((Convert.ToInt32(TBX_DMin2.Text) * 60 + Convert.ToInt32(TBX_DSec2.Text)) < 3)
                    m_errMsg += "Duration must be more than 3 sec";

                if (indexOfAsset.SelectedIndex == -1)
                    m_errMsg +="Please Choose a Asset to be Edited \n";
                if (ingestFromPathOfExistingAsset.Text == "Ingested From Path" || ingestFromPathOfExistingAsset.Text == "")
                    m_errMsg += "Please Choose a Source to be Ingested into an Asset \n";
                if(!File.Exists(ingestFromPathOfExistingAsset.Text)&&!Directory.Exists(ingestFromPathOfExistingAsset.Text))
                    m_errMsg += "The File/Directory is not exist! Please Check the address !";


                overlayPath = overlayImagePathOfExisitingAsset.Text;
                transparent = transparentForExisitingAsset.Text;
            }

            //Test if the overlay Image is valid and if the Transparent % number is valid
            if (overlayPath != "Overlay Image Path" && overlayPath != "")
            {
                if (!File.Exists(overlayPath))
                    m_errMsg += "The Overlay Image Path is not valid !";
            }
            else if (File.Exists(overlayPath) && !Information.IsNumeric(transparent))
            {
                m_errMsg += "Please Enter a Valid Number for Transparent % \n";
                transparentDegree.Text = "1~100";
                transparentForExisitingAsset.Text = "1~100";
            }
            else if (transparent != "1~100" && !Information.IsNumeric(transparent))
            {
                m_errMsg += "Please Enter a Valid Number for Transparent % \n";
                transparentDegree.Text = "1~100";
                transparentForExisitingAsset.Text = "1~100";
            }

            //If there is error , call the displayError fucntion and reset the errMsg;
            if (m_errMsg != "")
            {
                displayError(m_errMsg);
                m_errMsg = "";
                createNewAsset.Enabled = true;
                ingestFrameSequenceToAsset.Enabled = true;
            }
        }

        /// <summary>
        /// Report Error and delete the imcomplete Asset
        /// Call by the createNewAsset click event
        /// When Error is rised
        /// </summary>
        /// <param name="index"></param>
        private void ErrorReport(int index)
        {
            string command;

            if (index == 1)
                m_errMsg += "Cannot access source Folder/File.";
            else if (index == 2)
                m_errMsg += "You must select a folder containing the images to be assembled into an Asset.";
           
            if(index != 0)
                displayError(m_errMsg);
            //Reset the error Message
            m_errMsg = "";

            //Delete the new created AssetID by calling the stored procedure
            if (MediaIngestion.SelectedIndex == 0 && index == 0)
            {
                if (m_UseExistAssetID != 0)
                {
                    command = "sproc_ATC_del_Asset_Error @ID =" + m_UseExistAssetID;
                    UpdateDataBase(command);
                }
            }

            EnableAssetButton();

        }

        /// <summary>
        /// Will Ingest the video into the Media for each slice of selected player
        /// CreateNewAsset button Click event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void createNewAsset_Click(object sender, EventArgs e)
        {
            createNewAsset.Enabled = false;
            int mediaID;
            int playerID;
            int cancelCount = 0;
            string sourceFolder;
            Media md = new Media();
            string command;
            ArrayList MediaSet = new ArrayList();
            bool createMedia =false;
            

            CheckInput(); // check the input;

            //stop if there is a error occurred , stop ; otherwise procced
            if (m_ErrorOccurred)
            {
                m_ErrorOccurred = false;
                return;
            }
           
            //Check for each slice of image against database and ask user if the image is requried
            for (int sliceIndex = 1; sliceIndex <= m_TotalSlices; sliceIndex++)
            {
                mediaID = CheckSlice(sliceIndex, IngestedFromPath.Text, m_TotalSlices);
                if (mediaID == -1)
                {
                    sourceFolder = CreateSourceFolder(sliceIndex, playerIndexedOrAll.SelectedIndex, newAssetName.Text); //Create the Folder 
                    md.mediaID = -1;
                    md.sliceIndex = sliceIndex;
                    md.sourceFolder = sourceFolder;

                    createMedia = true;
                }
                else
                {
                    md.mediaID = mediaID;
                    md.sliceIndex = sliceIndex;
                }
                MediaSet.Add(md);

                if (mediaID == -2)
                    cancelCount++;
            }

            if (createMedia)
            {
                m_UseExistAssetName = newAssetName.Text;

                //Process the File according to the MediaSet
                ProcessSourceFile(IngestedFromPath.Text, assetImageOverlayPath.Text, transparentDegree.Text, MediaSet);

                //Wait for the ingestion if no error occurred 
                if (!m_ErrorOccurred)
                    WaitToComplete(MediaSet);
            }

            if (m_ErrorOccurred)
            {
                m_ErrorOccurred = false;
                EnableAssetButton();
                return;
            }

            //Create the Asset with given AssetName and assigned the new Asset ID to the Global varable "useExistAssetID"
            if (cancelCount != m_TotalSlices)
            {
                m_UseExistAssetID = CreateAsset(newAssetName.Text, TBX_DMin.Text, TBX_DSec.Text);

                foreach (object mOb in MediaSet)
                {
                    md = (Media)mOb;
                    //mediaID == -1 indicates that the user choose to create the new media
                    if (md.mediaID == -1)
                    {
                        //Check if error occurred
                        if (m_ErrorOccurred)
                        {
                            m_ErrorOccurred = false; //reset the flag
                            //Call ErrorReport function to delete and reset the new create Asset
                            ErrorReport(0);
                            break;
                        }
                        else
                            md.mediaID = CreateMedia(md.sourceFolder, md.sliceIndex, m_TotalSlices, IngestedFromPath.Text); //Create the new Media if no error occurred
                    }

                    //Check for the specific player that is going to be displayed
                    if (playerIndexedOrAll.SelectedIndex != 0)
                    {
                        command = "Select ID from Player Where ChannelID =" + channelID.SelectedIndex + " and PlayerIndex = " + playerIndexedOrAll.SelectedIndex;
                        //Create the mediaID = "NULL" for rest of the players that are not chosen to be displayed
                        CreateEmptyMediainstance(m_UseExistAssetID);
                    }
                    else
                        command = "Select ID from Player Where ChannelID =" + channelID.SelectedIndex + " and PlayerIndex = " + md.sliceIndex;
                    playerID = Convert.ToInt32(getDataObject(command));

                    //if the user choose to cancel the process , the mediaID = NULL" will be created for that particular slice
                    if (md.mediaID == -2)
                        CreateMediainstance(m_UseExistAssetID, playerID);
                    else CreateMediainstance(m_UseExistAssetID, playerID, md.mediaID.ToString()); // otherwise , created the respective Mediainstance for each media

                }
            }

            //Reset the ProgressBar to zero
            m_Percentage = 0;
            progressBar1.Value = 0;

            //Reload the Existing Asset List
            inistialExistingList();

            EnableAssetButton();
        }

        private void EnableAssetButton()
        {
            createNewAsset.Enabled = true;
            ingestFrameSequenceToAsset.Enabled = true;
        }

        /// <summary>
        /// Main thread wait for the child thread to complete before create the ASSET in the Database
        /// Call by the Create Asset Button Event
        /// </summary>
        /// <param name="mediaSet"></param>
        private void WaitToComplete(ArrayList mediaSet)
        {
            //Update the procgress if the ingestion has not completed
            m_ExtractComplete = true;
            while (!m_IngestionComplete)
            {
                Thread.CurrentThread.Join(500);
                displayProgress();
            }

            progressBar1.Value = 0;
            progressBar2.Value = 0;

            EnableAssetButton();

            Distribution.Distribution.ErrorTrace trace = new Distribution.Distribution.ErrorTrace(displayError);

            m_Go.Init(m_ConnectionString, trace);

            m_Ingesting = false;
            m_MainTComplete = false;
            m_IngestionComplete = false;

            try
            {
                if (m_TotalFrames < 0)
                {
                    foreach (Media mediaOb in mediaSet)
                        Directory.Delete(mediaOb.sourceFolder, true);
                    m_ErrorOccurred = true;
                }
            }
            catch (Exception err)
            {
                string errMsg = "The Media source folder is been used when trying to delete it due to User Cancel or Error Occured";
                displayError(errMsg + err);
            }
        }

        private bool ChooseInterlace(int width, int height)
        {
            if (m_ForceNotInterlace)
                return false;
            else
            {
                if ((width == 1920 && height == 1080)|| (width == 720 && height == 486))
                    return true;
                else
                    return false;
            }
        }

        private void LoadImageSize(int width, int height)
        {
            if (m_Display == 1)
            {
                if (width == 1280 && height == 720)
                    m_SameSize = true;
                else
                    m_SameSize = false;

                m_FrameCal.MitsuResize(m_OutputFormat, (double)width, (double)height, out m_Left_STW, out m_Left_STH, out m_Left_LW, out m_Left_LH, out m_RectWStart, out m_RectHStart, out m_RectWidth, out m_RectHight);
            }
            else if (m_Display == 2)
            {
                if (!m_TwoRibbonStrech)
                    m_FrameCal.RibbonResize(m_OutputFormat, (double)width, (double)height, out m_Left_STW, out m_Left_STH, out m_Left_LW, out m_Left_LH, out m_Right_STW, out m_Right_STH, out m_Right_LW, out m_Right_LH, out m_RectWStart, out m_RectHStart, out m_RectWidth, out m_RectHight);
                else
                    m_FrameCal.FullStrech(m_OutputFormat, (double)width, (double)height, out m_Left_STW, out m_Left_STH, out m_Left_LW, out m_Left_LH, out m_Right_STW, out m_Right_STH, out m_Right_LW, out m_Right_LH, out m_RectWStart, out m_RectHStart, out m_RectWidth, out m_RectHight);
            }
            else if (m_Display == 3)
            {
                m_FrameCal.GetTickerFrame(Convert.ToDouble(width), Convert.ToDouble(height), out m_RectHight);
            }
        }

        /// <summary>
        /// Image Processing , cut the extracted picture into the pieces that requried by the player
        /// call by ProcessSourceFile()
        /// after the video Ingestion function has been called
        /// ***may have memory leaking problem
        /// </summary>
        /// <param name="mediaSetOb"></param>
        private void ImageProcess (object mediaSetOb)
        {
            XYThreadPool imagePool = new XYThreadPool();
            DoublePixel.DoublePixel dbP = new DoublePixel.DoublePixel();
            imagePool.StartThreadPool(20, 30);
            ArrayList mediaSet = (ArrayList)mediaSetOb;
            string tempFramePath = (string)mediaSet[mediaSet.Count - 1];
            mediaSet.RemoveAt(mediaSet.Count - 1);
            DirectoryInfo dir = new DirectoryInfo(tempFramePath);
            FileInfo[] files = dir.GetFiles();
            ImageOverLay overlayOb = new ImageOverLay();
            m_Interlacing = false; //Offset for interlace process (DoublePixel library function)
            bool processFlag = true;
            int flagCounter = 1;
            int threadCount = 5;
            string nextFileNoPath="";


            imageCut iC = new imageCut(ImageSaving);

            //Check if any image file is extracted from the video ingestion

            if (!m_IngestFromFolder)
            {
                while (files.Length < 50 && m_TotalFrames != -1)
                {
                    Thread.Sleep(3000);
                    files = dir.GetFiles();
                }
            }

            if (m_TotalFrames != -1)
            {
                int x=0;
                while (files[x].Extension.ToLower() != ".jpg")
                {
                    x++;
                }
                Image testFrame;

                try
                {
                    testFrame = ImageFast.ImageFast.FromFile(tempFramePath + "\\" + files[x].Name);

                    if (!m_IngestFromFolder)
                    {
                        m_Interlacing = ChooseInterlace(testFrame.Width, testFrame.Height);
                        LoadImageSize(testFrame.Width, testFrame.Height);
                    }

                    testFrame.Dispose();
                }
                catch (Exception err)
                {
                    m_TotalFrames = -1;
                    m_errMsg += err.Message;
                }
            }

            int doubleFrame = m_TotalFrames * 2; //double the total frame size



            if (m_Display == 1)
            {
                threadCount = 8;
            }

            for (; m_Percentage < m_TotalFrames; m_Percentage++)
            {
                //check the type of image file
                try
                {
                    string fName = files[m_Percentage].Name;
                    string path = tempFramePath + "\\" + fName;
                    ArrayList newMediaSet2 = new ArrayList();

                    if (files[m_Percentage].Extension.ToLower() == ".bmp" || files[m_Percentage].Extension.ToLower() == ".jpg" || files[m_Percentage].Extension.ToLower() == ".jpeg")
                    {
                        if (!File.Exists(path))
                            Thread.Sleep(2000);
                        Image tempImage2 = ImageFast.ImageFast.FromFile(path); //Use Imagefast Library to read local file into image object

                        string suffix;

                        //Check if applied overlay is required
                        if (m_Overlayflag)
                        {
                            try
                            {
                                overlayOb.OverlayImage(tempImage2, m_OverlayImage, m_Transdegree);
                            }
                            catch (Exception err)
                            {
                                m_errMsg += err;
                                displayError(m_errMsg);
                                break;
                            }
                        }
                        //Check if interlacing is required
                        if (m_Interlacing)
                        {
                            m_MitsuDoubleFrame = false;

                            //Create new duplicated Image
                            Bitmap orignialImage = new Bitmap(tempImage2);
                            //Separated the two image

                            if (m_Display == 1)
                            {
                                Image tempImage1 = dbP.FrameExtract((Bitmap)tempImage2, 1);

                                //Create new set of ArrayList 
                                ArrayList newMediaSet1 = new ArrayList();
                                foreach (Media md in mediaSet)
                                    newMediaSet1.Add(md);
                                newMediaSet1.Add(tempImage1);

                                //Calculate the file name
                                int fileNo = (m_Percentage - 1) * 2 + 2;
                                GetSuffix(fileNo.ToString().Length, out suffix);
                                newMediaSet1.Add(suffix + fileNo + ".jpg"); //Give Proper File Name

                                //Start Ingesting the Image
                                if(m_IngestFromFolder)
                                    ImageSaving((object)newMediaSet1);

                                else 
                                    ThreadPool.QueueUserWorkItem(new WaitCallback(ImageSaving), (object)newMediaSet1);
                                //ImageSaving((object)newMediaSet1);


                                fileNo = (m_Percentage - 1) * 2 + 3;
                                GetSuffix(fileNo.ToString().Length, out suffix);
                                fName = suffix + fileNo + ".jpg";
                            }
                            else
                            {
                                GetSuffix(m_Percentage.ToString().Length, out suffix);
                                fName = suffix + m_Percentage + ".jpg";
                            }
                            //Set the second frame 
                            tempImage2 = dbP.FrameExtract(orignialImage, 2);
                            //processFlag = true; //Set To Create New Thread to process Image all the time
                        }
                        else
                        {
                            int fileNo;
                            int fileNextNo;

                            if (m_MitsuDoubleFrame)
                            {
                                fileNo = (m_Percentage - 1) * 2 + 2;
                                fileNextNo = fileNo + 1;
                                GetSuffix(fileNextNo.ToString().Length, out suffix);
                                nextFileNoPath = suffix + fileNextNo + ".jpg";
                            }
                            else
                                fileNo = m_Percentage;

                            GetSuffix(fileNo.ToString().Length, out suffix);
                            fName = suffix + fileNo + ".jpg";

                        }
                        foreach (Media md in mediaSet)
                            newMediaSet2.Add(md);

                        newMediaSet2.Add(tempImage2);
                        newMediaSet2.Add(fName);

                        if (m_MitsuDoubleFrame)
                            newMediaSet2.Add(nextFileNoPath);

                        //Start a new thread to the image Processing
                        if (processFlag)
                        {
                            //ThreadPool.QueueUserWorkItem(new WaitCallback(ImageSaving), (object)newMediaSet2);
                            if(m_IngestFromFolder)
                                ImageSaving((object)newMediaSet2);
                            else 
                                imagePool.InsertWorkItem("CutImage", iC, new Object[1] { newMediaSet2 }, false);
                            //ImageSaving((object)newMediaSet2);

                            flagCounter++;
                            if (flagCounter > threadCount)
                            {
                                processFlag = false;
                                if (m_ExtractComplete)
                                {
                                    Thread.CurrentThread.Priority = ThreadPriority.Highest;
                                }
                                if (m_IngestFromFolder)
                                {
                                    displayProgress();
                                    //Thread.CurrentThread.Join(10000);
                                }
                                

                                flagCounter = 1;
                            }
                        }
                        else
                        {
                            ImageSaving((object)newMediaSet2);
                            processFlag = true;
                        }
                            
                        //ImageSaving((object)newMediaSet2);
                    }
                   //Thread.Sleep(100);
                }
                catch (IndexOutOfRangeException er) //When the Index is out of range, re-check the temp file directory for the right amount of file present
                {
                    files = dir.GetFiles();
                    m_Percentage--;
                    if(!m_IngestionComplete)
                        Thread.Sleep(10000);
                    
                }
                catch (Exception err)
                {
                    m_errMsg += err;
                    //MessageBox.Show(m_errMsg);
                }
            }
           
            //MessageBox.Show(m_Quality.ToString());
            try
            {
                Thread.Sleep(3000);



                //If the process being Stop or Error Occurred during Video Extraction
                //Remove all the files had been created


                if (m_TotalFrames < 0)
                    Thread.CurrentThread.Abort();

                if (m_MitsuDoubleFrame)
                    m_TotalFrames = doubleFrame;

                if (m_Interlacing && m_Display == 1)
                    m_TotalFrames = doubleFrame;

                if (!m_IngestFromFolder)
                    Directory.Delete(tempFramePath, true);

            }
            catch (Exception err)
            {
                //Thread.Sleep(20000);
                //if (!ingestedFromFolder)
                //    Directory.Delete(tempFramePath, true);
            }
            finally
            {
                m_IngestFromFolder = false;
                m_ExtractComplete = false;
                m_Percentage = 0;
                m_IngestionComplete = true;
            }
        }

        /// <summary>
        /// Get the suffix for naming
        /// call by ImageProcess
        /// before image is processing
        /// </summary>
        /// <param name="length"></param>
        /// <param name="suffix"></param>
        private void GetSuffix(int length, out string suffix)
        {
            suffix = "";
            for (int j = 0; j < ( 6 - length); j++)
                suffix = suffix + '0';
        }
        

        /// <summary>
        /// Processing the Image Ingesting and save the file
        /// call by ImageProcess
        /// After the overlay image has been appied
        /// </summary>
        /// <param name="ob"></param>
        public void ImageSaving(object ob)
        {
            Thread.CurrentThread.Priority = ThreadPriority.Highest;
            ArrayList newMediaSet = (ArrayList)ob;
            string fileNextName = "";
            //Get the NextFileName if MituDoubleFrame applied
            if (m_MitsuDoubleFrame)
            {
                fileNextName = (string)newMediaSet[newMediaSet.Count - 1];
                newMediaSet.RemoveAt(newMediaSet.Count - 1);
            }
            //Get the File Name
            string fileName = (string)newMediaSet[newMediaSet.Count - 1];
            newMediaSet.RemoveAt(newMediaSet.Count - 1);
            //Get the Image object
            Image localSource = (Image)newMediaSet[newMediaSet.Count - 1];
            newMediaSet.RemoveAt(newMediaSet.Count - 1);
            //Create the array for Image Ingestion Library 
            int[] sliceIndex = new int[newMediaSet.Count];
            string[] filePath = new string[newMediaSet.Count];
            ImageIngestion.disPlayError trace = new ImageIngestion.disPlayError(displayError);
            ImageIngestion.downQuality downQ = new ImageIngestion.downQuality(downQuality);

            //Assign the Array with required info by image Ingestion Object
            for (int i = 0; i < newMediaSet.Count; i++)
            {
                Media md = (Media)newMediaSet[i];
                if (md.mediaID == -1)
                {
                    sliceIndex[i] = md.sliceIndex;
                    filePath[i] = md.sourceFolder + "\\" + fileName;
                    if (m_MitsuDoubleFrame)
                        fileNextName = md.sourceFolder + "\\" + fileNextName;
                }
            }

            if (m_IngestFromFolder)
                LoadImageSize(localSource.Width, localSource.Height);
            //Start Image Ingestiong
            if (m_Display == 1)
            {
                m_imageingestOb.MitsuResize(fileNextName, m_SameSize, localSource, ((Media)newMediaSet[0]).sourceFolder + "\\" + fileName, m_Quality, m_Left_STW, m_Left_STH, m_Left_LW, m_Left_LH,m_RectWStart, m_RectHStart, m_RectWidth, m_RectHight, trace, downQ);

            }
            else if (m_Display == 2)
            {
                m_imageingestOb.RibbonDivide(localSource, m_Left_STW, m_Left_STH, m_Left_LW, m_Left_LH, m_Right_STW, m_Right_STH, m_Right_LW, m_Right_LH, sliceIndex, filePath, m_RectWStart, m_RectHStart, m_RectWidth, m_RectHight, m_Quality , trace, downQ);
            }
            else
            {
                m_imageingestOb.TickerResize(localSource, m_RectHight, sliceIndex, filePath, m_Quality, trace, downQ);
                //imageingestOb.DivideImage(m_TotalSlices, localSource, m_FrameWidth, m_FrameHight, sliceIndex, filePath, trace);
            }
            localSource.Dispose();
        }

        /// <summary>
        /// Create Mediaid = ID for others player that were not selected by the user
        /// Call by the CreateAsset Event Buttn
        /// </summary>
        /// <param name="assetID"></param>
        private void CreateEmptyMediainstance(int assetID)
        {
            DataSet ds = new DataSet();
            string command = "Select ID, PlayerIndex From Player Where ChannelID =" + channelID.SelectedIndex;

            ds = OpenConnection(command, "PlayerID");

            foreach (DataRow row in ds.Tables["PlayerID"].Rows)
            {
                if (Convert.ToInt32(row["PlayerIndex"]) != playerIndexedOrAll.SelectedIndex)
                    CreateMediainstance(assetID, Convert.ToInt32(row["ID"]));
            }
        }

        private int GetRibbons()
        {
            if (MediaIngestion.SelectedIndex == 1)
            {
                if(m_ExistAssetChannelID == 2)
                    return 2;
                if (m_ExistAssetChannelID == 1)
                    return 1;
            }
            if (MediaIngestion.SelectedIndex == 0)
            {
                if(channelID.SelectedIndex == 2)
                    return 2;
                if (channelID.SelectedIndex == 1)
                    return 1;
            }

            return 3;
        }

        /// <summary>
        /// Major function for process the Video Ingestion, decide the process that requried to process the video or the image sequences
        /// call by both CreateAsset and IngestAsset Click event
        /// </summary>
        /// <param name="IngestedPath"></param>
        /// <param name="overlayPath"></param>
        /// <param name="transparent"></param>
        /// <param name="mediaSet"></param>
        private void ProcessSourceFile(string IngestedPath, string overlayPath,string transparent, ArrayList mediaSet)
        {
            m_Go.CloseAll();
            
            m_Quality = 100;
            m_Ingesting = true;
            VideoIngestion.updateFrame giveTotalFrame = new VideoIngestion.updateFrame(updateFrame); // for delegate function
            VideoIngestion.disPlayDelegate trace = new VideoIngestion.disPlayDelegate(displayError); // for display error delegate function

            if (m_CamOb != null)
                m_CamOb.Dispose();

            //if the overlay image are present with correct transparent % input, set the flag to true
            ApplyOverLayImage(overlayPath, transparent);

            //check if the video file are presented
            if (File.Exists(IngestedPath)&& !m_ErrorOccurred)
            {
                string tempAssetName;

                if (m_UseExistAssetName.Length > 40)
                    tempAssetName = m_UseExistAssetName.Remove(40);
                else
                    tempAssetName = m_UseExistAssetName;

                string tmpFramePath = m_VideoStorePath + "\\TempFolder\\" + tempAssetName;

                if (!Directory.Exists(tmpFramePath))
                    Directory.CreateDirectory(tmpFramePath);
                else
                {
                    Directory.Delete(tmpFramePath, true);
                    Directory.CreateDirectory(tmpFramePath);
                }

                mediaSet.Add(tmpFramePath);

                //Start New Thread to Start processing the image File that will be extracted by the vIob.Extract
                ThreadPool.QueueUserWorkItem(ImageProcess, (object)mediaSet);
                //ImageProcess((object)mediaSet);
                string sqlCommand = "Select Value from Globalconfig where Property = 'AudioStorePath'";
                string audioName = getDataObject(sqlCommand).ToString() + "\\" + m_UseExistAssetName + ".wav";

                m_vIob.ExtractImage((m_Display == 2 || m_Display == 3), IngestedPath, tmpFramePath, audioName, giveTotalFrame, trace);

            }
            //check if the image sequance folder are present
            else if (Directory.Exists(IngestedPath)&&!m_ErrorOccurred)
            {
                DirectoryInfo dir = new DirectoryInfo(IngestedPath);

                if (File.Exists(IngestedPath + "\\Thumbs.db"))
                    File.Delete(IngestedPath + "\\Thumbs.db");

                m_FileCountOffset = false;

                FileInfo[] files = dir.GetFiles();
                bool fileFound = false;

                foreach (FileInfo file in files)
                {
                    if (file.Extension.ToLower() == ".jpeg" || file.Extension.ToLower() == ".jpg" || file.Extension.ToLower() == ".bmp")
                    {
                        fileFound = true;
                        break;
                    }
                }
                //if the folder doesn't exist a valid image file, report error
                if (fileFound)
                {
                    m_TotalFrames = files.Length;
                    mediaSet.Add(IngestedPath);
                    m_IngestFromFolder = true;
                    //ThreadPool.QueueUserWorkItem(ImageProcess, (object)mediaSet);
                    ImageProcess((object)mediaSet);
                }
                else
                    ErrorReport(2);

            }
            else
            {
                if (IngestedPath == "Ingested From Path")
                    ErrorReport(2);
                else if (m_ErrorOccurred)
                    ErrorReport(3);
                else ErrorReport(1);

                //delete the new create folder for image to be saved
                foreach (Media mediaOb in mediaSet)
                    Directory.Delete(mediaOb.sourceFolder);
            }
            m_MainTComplete = true;
        }


        /// <summary>
        /// Insert the new Media data into the database
        /// Call by both Button of Create Asset and Ingest to Current Asset button Event
        /// </summary>
        /// <param name="sourceFolder"></param>
        /// <param name="sliceIndex"></param>
        /// <param name="sliceCount"></param>
        /// <param name="ingestedPath"></param>
        /// <returns></returns>
        private int CreateMedia(string sourceFolder , int sliceIndex, int sliceCount, string ingestedPath)
        {
            ingestedPath = NameFilter(ingestedPath);

            int mediaID;

            string[] foldernames = sourceFolder.Split('\\');
            string fName = foldernames[foldernames.Length - 1];

            if (m_FileCountOffset && m_Interlacing && m_Display ==1)
                m_TotalFrames -= 2;
            else if(m_FileCountOffset)
                m_TotalFrames -= 1;

            string command = "sproc_ATC_Insert_Media @IsFrameSequence = 'true', @SourcePath ='" + fName + "', @FileCount = " + m_TotalFrames + ", @IsImageSet = '" + m_ImageSlide.ToString() + "' , @IngestedFromPath ='" + ingestedPath + "', @Height = " + m_FrameHight.ToString() + ", @Width =" + m_FrameWidth.ToString() + ", @SliceIndex =" + sliceIndex.ToString() + ", @SliceCount=" + sliceCount.ToString() + ", @UserID=" + m_UserID;
            mediaID = Convert.ToInt32(getDataObject(command));

            return mediaID;
        }

        /// <summary>
        /// Insert the new Asset into the database
        /// Called by Create Asset button Event
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        private int CreateAsset(string name, string cMin, string cSec )
        {
            int assetID;
            string CueStringStart;
            if (m_Display == 1)
                CueStringStart = "Source.Mitsu(10)";
            else if (m_Display == 2)
                CueStringStart = "Source.Ribbons(" + CoBox_VideoSoure.SelectedValue + ")";
            else
                CueStringStart = "Source.Tickers(70)";

            string command = "sproc_ATC_Insert_Asset @Name='" + name + "', @Duration ='00:" + cMin + ":" + cSec + "', @ChannelsNN = '," + channelID.SelectedIndex.ToString().Trim() + ",', " + "@CueStringStart='" + CueStringStart + "', @IsCombo='false' ,@ThisEnabled ='true',@EnabledNN ='true' , @IngestedNN='true' , @OnPlayersNN= 'false' ,@UserID=" + m_UserID;
            assetID = Convert.ToInt32(getDataObject(command));

            return assetID;
        }

        //Insert the Mediainstance with MediaID = "0"
        private void CreateMediainstance(int assetID, int playerID)
        {
            string command = "sproc_ATC_Insert_MediaInstance2 @AssetID =" + assetID + ", @PlayerID =" + playerID + ", @Enabled = 'true', @TransferPriority = 1,@FilesPresentNN = 0,@FullyPresentNN ='false' ,@UserID=" + m_UserID;
            UpdateDataBase(command);
        }

        //Insert the Mediainstance with givin MediaID
        private void CreateMediainstance(int assetID, int playerID, string mediaID)
        { 
            string command;
            command = "sproc_ATC_Insert_MediaInstance @AssetID =" + assetID + ", @PlayerID =" + playerID + " ,@MediaID ='" + mediaID + "', @Enabled = 'true', @TransferPriority = 1,@FilesPresentNN = 0,@FullyPresentNN ='false',@UserID=" + m_UserID;
            UpdateDataBase(command);

        }

        //Update the Mediainstance
        private void CreateMediainstaceUpdate(int assetID, int playerID, int mediaID)
        {
            string command = "sproc_ATC_Insert_MediaInstanceUpdate @AssetID=" + assetID + ", @PlayerID =" + playerID + " ,@MediaID=" + mediaID + " ,@TransferPriority = 1 ,@FilesPresentNN =0 ,@FullyPresentNN = 'false',@UserID=" + m_UserID;
            UpdateDataBase(command);
        }

        //create the folder for image to be saved
        private string CreateSourceFolder(int sliceIndex, int pIndex, string assetName)
        {
            assetName = NameFilter(assetName).TrimEnd();

            int playerIndex;
            int version =1;
            string suffix_Name = "";

            if (m_Display == 1)
            {
                suffix_Name = "M_";
            }
            else if (m_Display == 2)
            {
                suffix_Name = "R_";
            }
            else if (m_Display == 3)
            {
                suffix_Name = "T_";
            }

            if (pIndex == 0)
                playerIndex = sliceIndex;
            else playerIndex = pIndex;
            string folderName = m_VideoStorePath + "\\" + suffix_Name + assetName + "_" + playerIndex.ToString() + "_";
            string sourceFolder = folderName + version.ToString();

            sourceFolder = NameFilter(sourceFolder);

            //Check the version
            while (Directory.Exists(sourceFolder))
            {
                version++;
                sourceFolder = folderName + version.ToString();
            }
            Directory.CreateDirectory(sourceFolder);

            return sourceFolder;
        }

        private string NameFilter(string beforeFilter)
        {
            beforeFilter = beforeFilter.Replace("'", "");
            beforeFilter = beforeFilter.Replace("~", "");
            beforeFilter = beforeFilter.Replace("!", "");
            beforeFilter = beforeFilter.Replace("@", "");
            beforeFilter = beforeFilter.Replace("#", "");
            beforeFilter = beforeFilter.Replace("$", "");
            beforeFilter = beforeFilter.Replace("%", "");
            beforeFilter = beforeFilter.Replace("^", "");
            beforeFilter = beforeFilter.Replace("&", "");
            beforeFilter = beforeFilter.Replace("*", "");
            beforeFilter = beforeFilter.Replace("(", "");
            beforeFilter = beforeFilter.Replace(")", "");
            beforeFilter = beforeFilter.Replace("-", "");
            beforeFilter = beforeFilter.Replace("+", "");
            beforeFilter = beforeFilter.Replace("{", "");
            beforeFilter = beforeFilter.Replace("}", "");

            return beforeFilter;
        }

        //Major function, Check if the slice is already exist and if the user choose to use it instead of creating the new media
        public int CheckSlice(int sliceIndex, string IngestedPath, int totalSlice)
        {
            m_Display = GetRibbons();

            IngestedPath = NameFilter(IngestedPath);

            DataSet ds = new DataSet();
            DataSet ds2 = new DataSet();
            int MediaID = -1;
            string command1 = "sproc_ATC_Sel_Media @SourcePath = '" + IngestedPath + "'";
            string command2 = "sproc_ATC_Sel_Media @IngestedFromPath ='" + IngestedPath + "'";


            //Check if the Ingested Source is the same with any Media.SourcePath with all the parameter match
            ds = OpenConnection(command1, "Media");
            if (ds != null)
            {
                foreach (DataRow row in ds.Tables["Media"].Rows)
                {
                    if (Directory.Exists(IngestedPath) && IngestedPath.Contains(m_VideoStorePath))
                    {
                        if (Convert.ToInt32(row["Height"]) == m_FrameHight && Convert.ToInt32(row["Width"]) == m_FrameWidth && Convert.ToInt32(row["SliceIndex"]) == sliceIndex && Convert.ToInt32(row["SliceCount"]) == totalSlice)
                        {
                            MediaID = Convert.ToInt32(row["ID"].ToString());
                            break;
                        }
                    }
                }
            }

            //if no mediaID found , check if the Media Ingested Path are the same
            if (MediaID == -1)
            {
                ds2 = OpenConnection(command2, "Media2");
                if (ds2 != null)
                {
                    foreach (DataRow row in ds2.Tables["Media2"].Rows)
                    {
                        if (Convert.ToInt32(row["Height"]) == m_FrameHight && Convert.ToInt32(row["Width"]) == m_FrameWidth && Convert.ToInt32(row["SliceIndex"]) == sliceIndex && Convert.ToInt32(row["SliceCount"]) == totalSlice)
                        {
                            string message;
                            string command3 = "sproc_ATC_FindMediaCreator @MediaID = " + Convert.ToInt32(row["ID"]);

                            DataSet dsuser = OpenConnection(command3, "User");

                            string userName = dsuser.Tables["User"].Rows[0]["UserName"].ToString();
                            string dateTime = dsuser.Tables["User"].Rows[0]["DateTime"].ToString();

                            if (userName == "")
                            {
                                userName = "Remote User";
                                dateTime = "Remote Time";
                            }

                            if (m_CurrentPlayerIndex == 0)
                                message = "PlayerIndex : " + sliceIndex + " , Use existing Media Ingested By " + userName + " on " + dateTime + " ?";
                            else
                                message = "PlayerIndex : " + m_CurrentPlayerIndex + " , Use existing Media Ingested By " + userName + " on " + dateTime + " ?";

                            //For MessageBox
                            string caption = "Confirm With User";
                            MessageBoxButtons buttons;
                            DialogResult result;

                            if (MediaIngestion.SelectedIndex == 0)
                                buttons = MessageBoxButtons.YesNoCancel;
                            else
                                buttons = MessageBoxButtons.YesNo;

                            result = MessageBox.Show(this, message, caption, buttons);
                            if (result == DialogResult.Yes)
                                MediaID = Convert.ToInt32(row["ID"]);
                            else if (result == DialogResult.Cancel)
                                MediaID = -2;

                            return MediaID;
                        }
                    }
                }
            }
            return MediaID;
        }
         
        //Get the SQL command and return single object item using DataReader to speed up the communication
        public object getDataObject(string selectSQL)
        {
            
            SqlConnection con = new SqlConnection(m_ConnectionString);
            SqlCommand cmd = new SqlCommand(selectSQL, con);
            SqlDataReader reader = null;
            object ob = new object();

            try
            {
                con.Open();
                reader = cmd.ExecuteReader();
                reader.Read();
                ob = reader[0];//Only read ONE data in the first of list
                reader.Close();
            }
            catch (SqlException err)
            {
                if(err.Number != 1205)
                    displayError("Error occur while connect to DataBase via DataReader, Check Connection : \n" + err);
            }
            finally
            {
                con.Close();
            }

            return ob;
        }

        //With Given SQL command and tableName , return the Dataset that included all the required data
        public DataSet OpenConnection(string command, string tableName)
        {
            SqlConnection myConnection = new SqlConnection(m_ConnectionString);
            SqlCommand myCommand = new SqlCommand();
            myCommand.Connection = myConnection;
            myCommand.CommandText = command;
            DataSet ds = new DataSet();
            SqlDataAdapter ad_data;

            try
            {
                myConnection.Open();
                ad_data = new SqlDataAdapter(myCommand);
                ad_data.Fill(ds, tableName);

            }
            catch (SqlException err)
            {
                if (err.Number != 1205)
                    displayError("Device Not Connected \n" + err);
            }
            finally
            {
                myConnection.Close();
            }

            return ds;
        }

        //Update the Database , no return object
        private void UpdateDataBase(string command)
        {
            SqlConnection con = new SqlConnection(m_ConnectionString);
            SqlCommand cmd = new SqlCommand(command, con);

            // Try to open the database and execute the update.
            try
            {
                con.Open();
                //MessageBox.Show("here");
                cmd.CommandTimeout = 60000;
                cmd.ExecuteNonQuery();
                //MessageBox.Show(command);
            }
            catch (Exception err)
            {
                //MessageBox.Show(command);
                displayError("Update SQL Connection Fail \n"+ err);
            }

            finally
            {
                con.Close();
            }

        }
        
        //Get the selected player's display Height and Width
        private void playerIndexedOrAll_SelectedIndexChanged(object sender, EventArgs e)
        {
            DataSet ds = new DataSet();
            string getPlayer;

            if (channelID.SelectedIndex != 0)
            {
                if (playerIndexedOrAll.SelectedIndex != 0)
                {
                    getPlayer = "sproc_ATC_Sel_Player_Size @Channel =" + Convert.ToInt32(channelID.SelectedIndex) + ", @PlayerIndex =" + playerIndexedOrAll.SelectedIndex;
                    m_TotalSlices = 1;
                    m_CurrentPlayerIndex = playerIndexedOrAll.SelectedIndex;
                }
                else
                {
                    getPlayer = "sproc_ATC_Sel_Player_Size @Channel =" + Convert.ToInt32(channelID.SelectedIndex);
                    m_CurrentPlayerIndex = 0;
                }
                ds = OpenConnection(getPlayer, "Player");
                m_FrameHight = Convert.ToInt32(ds.Tables["Player"].Rows[0]["Height"]);
                m_FrameWidth = Convert.ToInt32(ds.Tables["Player"].Rows[0]["Width"]);

                HardCode();
            }

            List<string> formatIndexSet = new List<string>();

            int defaultSelected = 0;

            if (channelID.SelectedIndex == 1)
            {
                formatIndexSet = AddDisplayFormat(1, 0);
                defaultSelected = 1;
            }
            else if (channelID.SelectedIndex == 2)
            {
                if (playerIndexedOrAll.SelectedIndex == 1)
                {
                    m_TwoRibbonStrech = false;
                    formatIndexSet = AddDisplayFormat(2, 1);
                    defaultSelected = 2;
                }
                else if (playerIndexedOrAll.SelectedIndex == 0)
                {
                    m_TwoRibbonStrech = true;
                    formatIndexSet = AddDisplayFormat(2, 0);
                    defaultSelected = 1;
                }
                else
                {
                    MessageBox.Show("No Right Ribbon Single output Avaible for Ingestion");
                    playerIndexedOrAll.SelectedIndex = 0;
                    formatIndexSet = AddDisplayFormat(2, 0);
                    defaultSelected = 1;
                }
            }
            else if (channelID.SelectedIndex == 3)
            {
                formatIndexSet.Add("ScaleWidth, Top Justify");
            }

            OutPut_NewAsset.DataSource = formatIndexSet;
            if(defaultSelected != 0)
                OutPut_NewAsset.SelectedIndex = defaultSelected;
        }

        private void OutPut_NewAsset_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (MediaIngestion.SelectedIndex == 0)
            {
                m_OutputFormat = OutPut_NewAsset.SelectedIndex + 1;
            }
            else
            {
                m_OutputFormat = OutPut_ExistAsset.SelectedIndex + 1;
            }
        }

        private void HardCode()
        {
            if (m_Display ==1)
            {
                m_FrameWidth = 1280;
                m_FrameHight = 720;
            }
        }

        private void browseIngestedFromPath_Click(object sender, EventArgs e)
        {
            if (m_FolderBrowserDialog1.ShowDialog() == DialogResult.OK)
                IngestedFromPath.Text = m_FolderBrowserDialog1.SelectedPath;
        }


        private void browseIngestedFromFile_Click(object sender, EventArgs e)
        {
            m_OpenFileDialog1.InitialDirectory = "Z:\\";
            //only QuitckTime Video
            m_OpenFileDialog1.Filter = "All File (*.*)|*.*| Audio Video Interleave (*.avi)|*.avi|QuickTime Movie (*.mov)|*.mov";
            m_OpenFileDialog1.FilterIndex = 1;
            m_OpenFileDialog1.RestoreDirectory = true;

            if (m_OpenFileDialog1.ShowDialog() == DialogResult.OK)
                IngestedFromPath.Text = m_OpenFileDialog1.FileName;
        }

        private void browseAssetOverlayImagePath_Click(object sender, EventArgs e)
        {
            m_OpenFileDialog1.InitialDirectory = "C:\\";
            m_OpenFileDialog1.Filter = "GIF Image File(*.gif)|*.gif|JPEG Image File(*.jpg)|*.jpg|All Files(*.*)|*.*";
            m_OpenFileDialog1.FilterIndex = 1;
            m_OpenFileDialog1.RestoreDirectory = false;

            if (m_OpenFileDialog1.ShowDialog() == DialogResult.OK)
                assetImageOverlayPath.Text = m_OpenFileDialog1.FileName;
        }

        private void transparentDegree_MouseClick(object sender, MouseEventArgs e)
        {
            transparentDegree.SelectAll();
        }

        //Show the progress of the video Ingestion 
        private void displayProgress()
        {
            if (MediaIngestion.SelectedIndex == 0)
            {
                try
                {
                    progressBar1.Value = Convert.ToInt32(((float)m_Percentage / m_TotalFrames) * 100);
                }
                catch
                {
                    progressBar1.Value = 0;
                }
            }
            else
            {
                try
                {
                    progressBar2.Value = Convert.ToInt32(((float)m_Percentage / m_TotalFrames) * 100);
                }
                catch
                {
                    progressBar2.Value = 0;
                }
            }
        }

        //The Delegate function for video Ingestion
        private void updateFrame(int totalframe, bool MitsuDoubleFrame)
        {
            m_TotalFrames = totalframe;

            m_MitsuDoubleFrame = MitsuDoubleFrame;
        }

        private void browseIngestedFromFolderForExistingAsset_Click(object sender, EventArgs e)
        {
            if (m_FolderBrowserDialog1.ShowDialog() == DialogResult.OK)
                ingestFromPathOfExistingAsset.Text = m_FolderBrowserDialog1.SelectedPath;
        }

        private void browseIngestFromFileOfExisitingAsset_Click(object sender, EventArgs e)
        {
            m_OpenFileDialog1.InitialDirectory = "Z:\\";
            m_OpenFileDialog1.Filter = "All File (*.*)|*.*|QuickTime Movie (*.mov)|*.mov|Audio Video Interleave (*.avi)|*.avi";
            m_OpenFileDialog1.FilterIndex = 1;
            m_OpenFileDialog1.RestoreDirectory = true;

            if (m_OpenFileDialog1.ShowDialog() == DialogResult.OK)
                ingestFromPathOfExistingAsset.Text = m_OpenFileDialog1.FileName;
        }

        private void browseOverlayImagePathForExisitingAsset_Click(object sender, EventArgs e)
        {
            m_OpenFileDialog1.InitialDirectory = "Z:\\";
            m_OpenFileDialog1.Filter = "GIF Image File(*.gif)|*.gif|JPEG Image File(*.jpg)|*.jpg|All Files(*.*)|*.*";
            m_OpenFileDialog1.FilterIndex = 1;
            m_OpenFileDialog1.RestoreDirectory = false;

            if (m_OpenFileDialog1.ShowDialog() == DialogResult.OK)
                overlayImagePathOfExisitingAsset.Text = m_OpenFileDialog1.FileName;
        }

        //Create the list of Asset and ChannelID to be displyed and selected
        private void inistialExistingList()
        {
            DataSet ds = new DataSet();

            //List<string> playerIndexSet = new List<string>();
            List<string> channelIndexSet = new List<string>();

            try
            {
                //Create the Asset List
                string command = "Select ID, Name From Asset Where IsCombo = 'false' order by Name";

                SetAssetList(command);

                //Create the Channel List
                command = "Select Name From Channel";
                ds = OpenConnection(command, "ChannelID");
                channelIndexSet.Add("Channel");

                foreach (DataRow row in ds.Tables["ChannelID"].Rows)
                    channelIndexSet.Add(row["Name"].ToString());

                //Set the datasource for the channel ComobBox
                channelID.DataSource = channelIndexSet;
            }
            catch (Exception err)
            {
                displayError("Inistialize Fail : " + err);
            }
        }

        private void SetAssetList(string command)
        {
            try
            {
                DataSet ds = new DataSet();
                DataSet ds2 = new DataSet();
                ds = OpenConnection(command, "AssetName");
                ds2 = OpenConnection(command, "AssetName2");

                //playerIndexSet.Add("List of Exisiting Asset");

                //foreach (DataRow row in ds.Tables["AssetName"].Rows)
                //    playerIndexSet.Add(row["Name"].ToString().TrimEnd(' '));

                //Set the datasource for the asset list ComboBox in two tabs
                
                CoBox_ListAsset.DisplayMember = "Name";
                CoBox_ListAsset.ValueMember = "ID";
                CoBox_ListAsset.DataSource = ds.Tables["AssetName"];

                indexOfAsset.DisplayMember = "Name";
                indexOfAsset.ValueMember = "ID";
                indexOfAsset.DataSource = ds2.Tables["AssetName2"];
            }
            catch (Exception err)
            {
                MessageBox.Show("Error on Loading Asset" + err);
                indexOfAsset.DataSource = null;
                CoBox_ListAsset.DataSource = null;
            }
        }

        //Set set the Player list according to the selected Channel.
        //Used by Existing Asset Tab
        private void SetPlayerIndexList(int channelID)
        {
            try
            {
                string getPlayersCountNN = "Select PlayersCountNN From Channel where ID =" + channelID.ToString();
                int playerCount = Convert.ToInt32(getDataObject(getPlayersCountNN));
                List<string> playerIndexSet = new List<string>();
                playerIndexSet.Add("Stretch To All");

                if (playerCount > 1)
                {
                    playerIndexSet.Add("Left Ribbon");
                    playerIndexSet.Add("Right Ribbon");
                }   

                playerIndexOrAllForExistingAsset.DataSource = playerIndexSet;

                GetOutPutFormat();
            }
            catch (Exception err)
            {
                displayError("Set Player Index List Fail : " + err);
            }
        }

        private void GetOutPutFormat()
        {
                List<string> formatIndexSet = new List<string>();

                int defaultIndex = 0;

                if (m_ExistAssetChannelID == 1)
                {
                    formatIndexSet = AddDisplayFormat(1, 0);
                    defaultIndex = 1;
                }
                else if (m_ExistAssetChannelID == 2)
                {
                    if (playerIndexOrAllForExistingAsset.SelectedIndex == 1)
                    {
                        formatIndexSet = AddDisplayFormat(2, 1);
                        defaultIndex = 2;
                    }
                    else if (playerIndexOrAllForExistingAsset.SelectedIndex == 0)
                    {
                        formatIndexSet = AddDisplayFormat(2, 0);
                        defaultIndex = 1;
                    }
                    else
                    {
                        MessageBox.Show("No Right Ribbon Single output Avaible for Ingestion");
                        playerIndexOrAllForExistingAsset.SelectedIndex = 0;
                        formatIndexSet = AddDisplayFormat(2, 0);
                        defaultIndex = 1;
                    }
                }
                else if (m_ExistAssetChannelID == 3)
                {
                    formatIndexSet.Add("ScaleWidth, Top Justify");
                }
                OutPut_ExistAsset.DataSource = formatIndexSet;

                if (defaultIndex != 0)
                    OutPut_ExistAsset.SelectedIndex = defaultIndex;
        }

        //Set the totalSlice for existing Asset and the Height/Width of selected Player
        private void playerIndexOrAllForExistingAsset_SelectedIndexChanged(object sender, EventArgs e)
        {
            DataSet ds = new DataSet();
            string getPlayer;

            if (playerIndexOrAllForExistingAsset.SelectedIndex != 0)
            {
                getPlayer = "sproc_ATC_Sel_Player_Size @Channel =" + m_ExistAssetChannelID.ToString() + ", @PlayerIndex =" + playerIndexOrAllForExistingAsset.SelectedIndex;
                m_TotalSlices = 1; 
                //Set the player that going to be displayed on
                m_CurrentPlayerIndex = playerIndexOrAllForExistingAsset.SelectedIndex;
            }
            else
            {
                getPlayer = "sproc_ATC_Sel_Player_Size @Channel =" + m_ExistAssetChannelID.ToString();
                string getPlayersCountNN = "Select PlayersCountNN From Channel where ID =" + m_ExistAssetChannelID;
                m_TotalSlices = Convert.ToInt32(getDataObject(getPlayersCountNN));
                //Set the player to be ALL
                m_CurrentPlayerIndex = 0;
            }
            ds = OpenConnection(getPlayer, "Player");
            m_FrameHight = Convert.ToInt32(ds.Tables["Player"].Rows[0]["Height"]);
            m_FrameWidth = Convert.ToInt32(ds.Tables["Player"].Rows[0]["Width"]);

            HardCode();

            GetOutPutFormat();
        }


        private void transparentForExisitingAsset_MouseClick(object sender, MouseEventArgs e)
        {
            transparentForExisitingAsset.SelectAll();
        }

        //Asset List of Existing Asset, assigned the used channel according to the chosen Asset
        private void indexOfAsset_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (indexOfAsset.SelectedIndex != -1)
            {
                DataSet ds = new DataSet();
                m_UseExistAssetName = indexOfAsset.Text;
                string command = "Select ID, ChannelsNN from Asset Where Name = '" + m_UseExistAssetName + "'";

                ds = OpenConnection(command, "Asset");
                m_UseExistAssetID = Convert.ToInt32(indexOfAsset.SelectedValue);
                m_ExistAssetChannelID = Convert.ToInt32(ds.Tables["Asset"].Rows[0]["ChannelsNN"].ToString()[1].ToString());
                SetPlayerIndexList(m_ExistAssetChannelID);
                lableChannelID.Text = "Channel ID : " + m_ExistAssetChannelID;
            }

        }

        //Event handler when Ingested into existing Asset button click
        private void ingestFrameSequenceToAsset_Click(object sender, EventArgs e)
        {
            int mediaID;
            string sourceFolder ="";
            Media md = new Media();
            bool createMedia = false;
            ArrayList MediaSet = new ArrayList();

            ingestFrameSequenceToAsset.Enabled = false;

            CheckInput();

            if (m_ErrorOccurred)
            {
                m_ErrorOccurred = false;
                return;
            }
            for (int sliceIndex = 1; sliceIndex <= m_TotalSlices; sliceIndex++)
            {
                mediaID = CheckSlice(sliceIndex, ingestFromPathOfExistingAsset.Text, m_TotalSlices);
                if (mediaID == -1)
                {
                    sourceFolder = CreateSourceFolder(sliceIndex, playerIndexOrAllForExistingAsset.SelectedIndex, m_UseExistAssetName);
                    md.mediaID = -1;
                    md.sliceIndex = sliceIndex;
                    md.sourceFolder = sourceFolder;

                    createMedia = true;
                }
                else
                {
                    md.mediaID = mediaID;
                    md.sliceIndex = sliceIndex;
                }
                MediaSet.Add(md);
            }

            if (createMedia)
            {
                ProcessSourceFile(ingestFromPathOfExistingAsset.Text, overlayImagePathOfExisitingAsset.Text, transparentForExisitingAsset.Text, MediaSet);
                //wait till the child thread finish image Processing
                if (!m_ErrorOccurred)
                    WaitToComplete(MediaSet);
            }

            if (m_ErrorOccurred)
            {
                m_ErrorOccurred = false;
                EnableAssetButton();
                return;
            }


            foreach (object mOb in MediaSet)
            {
                md = (Media)mOb;

                //Check if the new slice is existed already
                if (md.mediaID == -1)
                {
                    if (m_ErrorOccurred)
                    {
                        m_ErrorOccurred = false;
                        ErrorReport(0);
                        break;
                    }

                    //Create the new Media 
                    md.mediaID = CreateMedia(md.sourceFolder, md.sliceIndex, m_TotalSlices, ingestFromPathOfExistingAsset.Text);
                }
                //Update the mediainstance according to the new media ID
                UpdateMediaInstanceMediaID(md.sliceIndex, md.mediaID);
                UpdateAssetDuration();
            }
            inistialExistingList();
            m_Percentage = 0;
            progressBar2.Value = 0;

            EnableAssetButton();
        }

        private void UpdateAssetDuration()
        {
            string command = " Update Asset set Duration ='00:" + TBX_DMin2.Text + ":" + TBX_DSec2.Text + "' where ID=" + m_UseExistAssetID;
            UpdateDataBase(command);
        }

        //Update the MediaInstance, Mediainstanceupdate, MediainstanceDelete in the Database
        private void UpdateMediaInstanceMediaID(int sliceIndex, int mediaID)
        {
            DataSet ds = new DataSet();
            string command;

            if (playerIndexOrAllForExistingAsset.SelectedIndex ==0)
                command = "sproc_ATC_Sel_Mediainstance_ID @PlayerIndex =" + sliceIndex + ", @ChannelID = " + m_ExistAssetChannelID + ", @AssetID=" + m_UseExistAssetID;
            else
                command = "sproc_ATC_Sel_Mediainstance_ID @PlayerIndex =" + playerIndexOrAllForExistingAsset.SelectedIndex + ", @ChannelID = " + m_ExistAssetChannelID + ", @AssetID=" + m_UseExistAssetID;

            ds = OpenConnection(command, "Mediainstance");

            int mediainstanceID = Convert.ToInt32(ds.Tables["Mediainstance"].Rows[0]["ID"]);
            int playerID = Convert.ToInt32(ds.Tables["Mediainstance"].Rows[0]["PlayerID"]);
            string returnMediaID = ds.Tables["Mediainstance"].Rows[0]["MediaID"].ToString();
            int mediainstanceupdateID;
            
            //If the MediaID is "NULL" , update with new mediaID           
            if (returnMediaID == "")
            {
                command = "Update Mediainstance Set MediaID = " + mediaID + " Where ID = " + mediainstanceID;
                UpdateDataBase(command);
            }
            else
            {
                //Check if the Mediainstanceupdate is already exist for this mediaisntance
                command = "sproc_ATC_Sel_MediainstanceUpdate_Check @AssetID = " + m_UseExistAssetID + ", @PlayerID =" + playerID;
                mediainstanceupdateID = Convert.ToInt32(getDataObject(command));

                //if mediainstanceupdate exist, update the Mediainstanceupdate, update the Mediainstance and create new Mediainstancedelete all by the server side SQL script
                if (mediainstanceupdateID > 0)
                {
                    command = "sproc_ATC_Up_Mediainstanceupdate @MediaID = " + mediaID + ",@UpdateID=" + mediainstanceupdateID;
                    UpdateDataBase(command);
                }
                else
                    CreateMediainstaceUpdate(m_UseExistAssetID, playerID, mediaID);
            }
        }

        //Grab the parameter of the selected Asset 
        private void grabParams_Click(object sender, EventArgs e)
        {
            try
            {
                string command = "sproc_ATC_Sel_Asset_Media_Parameter @Name = '" + CoBox_ListAsset.Text + "'";
                DataSet ds = new DataSet();

                ds = OpenConnection(command, "Parameter");

                IngestedFromPath.Text = ds.Tables["Parameter"].Rows[0][0].ToString();
                channelID.SelectedIndex = Convert.ToInt32(ds.Tables["Parameter"].Rows[0][1].ToString()[1].ToString());
            }
            catch (Exception err)
            {
                displayError("Please Select An Asset First !! \n\n" + err);
            }
        }

        //Update the player index when the ChannelID is changed
        private void channelID_SelectedIndexChanged(object sender, EventArgs e)
        {
            List<string> playerIndexSet = new List<string>();

            if (channelID.SelectedIndex != 0)
            {
                string getPlayersCountNN = "Select PlayersCountNN From Channel where ID =" + Convert.ToInt32(channelID.SelectedIndex);
                m_TotalSlices = Convert.ToInt32(getDataObject(getPlayersCountNN));
                playerIndexSet.Add("Stretch To All");

                if (m_TotalSlices > 1)
                {
                   // for (int i = 1; i <= m_TotalSlices; i++)
                        playerIndexSet.Add("Left Ribbon");
                        playerIndexSet.Add("Right Ribbon");
                }
            }
            else
                playerIndexSet.Add("Please Select Channel First");

            playerIndexedOrAll.DataSource = playerIndexSet;

            CoBox_VideoSoure.DisplayMember = "DisplayText";
            CoBox_VideoSoure.ValueMember = "ItemValue";
            CoBox_VideoSoure.DataSource = VideoSourceOptions(channelID.SelectedIndex);
            
        }

        private ComboClass[] VideoSourceOptions(int channelID)
        {
            ComboClass[] dataSourceItems = null;

            if (channelID == 1)
            {
                ComboClass sourceItem = new ComboClass("10: Iridas 1/1", "10");
                dataSourceItems = new ComboClass[] { sourceItem };
                //dataSourceItems = {new ComboClass("10: Iridas 1/1", "10");};
            }
            else if (channelID == 2)
            {
                dataSourceItems = new ComboClass[6];

                ComboClass sourceItem = new ComboClass("30: IRIDAS 2/3", "30");
                dataSourceItems[0] = sourceItem;
                sourceItem = new ComboClass("33: IRIDAS 2 / Sweet LEFT", "33");
                dataSourceItems[1] = sourceItem;
                sourceItem = new ComboClass("34: IRIDAS 2/2", "34");
                dataSourceItems[2] = sourceItem;
                sourceItem = new ComboClass("47: IRIDAS 2 / Sweet RIGHT", "47");
                dataSourceItems[3] = sourceItem;
                sourceItem = new ComboClass("54: IRIDAS 2 / Sweet LEFT 2", "54");
                dataSourceItems[4] = sourceItem;
                sourceItem = new ComboClass("61: IRIDAS 2 / Sweet LEFT 3", "61");
                dataSourceItems[5] = sourceItem;
            }
            else if (channelID == 3)
            {
                ComboClass sourceItem = new ComboClass("70: Iridas 4", "70");
                dataSourceItems = new ComboClass[] { sourceItem };
            }

            return dataSourceItems;
        }


        private void advancedSetup(object deviceOB)
        {
            int hr = 0;

            IBaseFilter dev = (IBaseFilter)deviceOB;
            ISpecifyPropertyPages pProp = dev as ISpecifyPropertyPages;

            //Get the name of the filter from the FilterInfo struct
            FilterInfo filterInfo;
            hr = dev.QueryFilterInfo(out filterInfo);
            DsError.ThrowExceptionForHR(hr);

            // Get the propertypages from the property bag
            DsCAUUID caGUID;
            hr = pProp.GetPages(out caGUID);
            DsError.ThrowExceptionForHR(hr);

            //Create and display the OlePropertyFrame
            object oDevice = (object)dev;
            hr = OleCreatePropertyFrame(this.Handle, 0, 0, filterInfo.achName, 1, ref oDevice, caGUID.cElems, caGUID.pElems, 0, 0, IntPtr.Zero);
            DsError.ThrowExceptionForHR(hr);

            // Release COM objects
            Marshal.FreeCoTaskMem(caGUID.pElems);
            Marshal.ReleaseComObject(pProp);
            //Marshal.ReleaseComObject(filterInfo.pGraph);
        }

        //Capture event for Image capturing
        private void captureImageToNewImageInFolder_Click(object sender, EventArgs e)
        {
            string savingPath;

            if(m_CamOb == null)
                m_CamOb = new ImageCapture.Capture(m_Dvc, deckPanel);

            Cursor.Current = Cursors.WaitCursor;

            if (m_ip != IntPtr.Zero) 
            {
                Marshal.FreeCoTaskMem(m_ip);
                m_ip = IntPtr.Zero;
            }

            m_ip = m_CamOb.Click();

            //Load the captured image into Bitmap
            Bitmap pic = new Bitmap(m_CamOb.Width, m_CamOb.Height, m_CamOb.Stride, PixelFormat.Format24bppRgb, m_ip);
            //Rotate the image for currectly display
            pic.RotateFlip(RotateFlipType.RotateNoneFlipY);
            
            if (Directory.Exists(browser1.itemPath))
                savingPath = browser1.itemPath + "\\" + fileName.Text + ".jpg";
            else if (Directory.Exists(browser1.SelectedItem.Path))
                savingPath = browser1.SelectedItem.Path + "\\" + fileName.Text + ".jpg";
            else
            {
                displayError("Please Selected a Valided Folder!"); 
                Cursor.Current = Cursors.Default;
                return;
            }

            pic.Save(savingPath, ImageFormat.Jpeg);
            Cursor.Current = Cursors.Default;
        }


        private void priviewButton_Click(object sender, EventArgs e)
        {
            //Get the path of selected item and it's file extension
            string playPath = browser1.itemPath;
            string ext = browser1.itemExt.ToLower();

            //if it is a movie file, play with quickTime Controler , else use Picture Box to preview if it is a picture;
            //if (ext == ".avi" || ext == ".mov")
            //{
            //    picPreviewBox.Visible = false;
            //    axQTControl2.Visible = true;
            //    axQTControl2.URL = playPath;
            //}
            if (ext == ".jpg" || ext==".bmp" || ext==".gif")
            {
                axQTControl2.Visible = false;
                picPreviewBox.Visible = true;
                picPreviewBox.SizeMode = PictureBoxSizeMode.StretchImage;
                Image preImage = ImageFast.ImageFast.FromFile(playPath);

                //Find the OverlayImage 
                if (MediaIngestion.SelectedIndex == 0)
                {
                    ApplyOverLayImage(assetImageOverlayPath.Text, transparentDegree.Text);
                    if (m_Overlayflag)
                        m_Transdegree = Convert.ToInt32(transparentDegree.Text);
                }
                else
                {
                    ApplyOverLayImage(overlayImagePathOfExisitingAsset.Text, transparentForExisitingAsset.Text);
                    if (m_Overlayflag)
                        m_Transdegree = Convert.ToInt32(transparentForExisitingAsset.Text);
                }

                //if there is overlayimage present , apply overlay on the image
                if (m_Overlayflag)
                {
                    ImageOverLay overlayOb = new ImageOverLay();
                    try
                    {
                        overlayOb.OverlayImage(preImage, m_OverlayImage, m_Transdegree);
                    }
                    catch (Exception err)
                    {
                        m_errMsg += err;
                        displayError(m_errMsg);
                    }
                }
                //Assign the picture box with the image
                picPreviewBox.Image = preImage;
            }
            else
            {
                MessageBox.Show("File Format is not Supported ! ");
            }
        }

        //Function to check fi the overlayimage is present
        private void ApplyOverLayImage(string path, string number)
        {
            if (File.Exists(path) && Information.IsNumeric(number))
            {
                m_Overlayflag = true;
                try
                {
                    //check if the image file are formated correctly
                    m_OverlayImage = Image.FromFile(path);
                    m_Transdegree = Convert.ToInt32(number);
                }
                catch (Exception err)
                {
                    m_errMsg += "Overlay Image is not formated Currectlly and Cannot Load Image File \n\n" + err;
                    m_ErrorOccurred = true;
                }
            }
            else m_Overlayflag = false;
        }

 
        private void CheckIdle(object dumpOb)
        {

            if (!m_Go.paused && (m_Capturing || m_DeckFinding))
            {
                m_Go.Pause();
                UpdateDataBase("Update Globalconfig set Value = 'false' where Property = 'AssetThumbnailOffset'");
            }
            else if (m_Go.paused && !m_PauseByUser && !m_Capturing && !m_DeckFinding)
            {
                m_Go.UnPause();
                UpdateDataBase("Update Globalconfig set Value = 'true' where Property = 'AssetThumbnailOffset'");
            }
            Thread.Sleep(5000);
            ThreadPool.QueueUserWorkItem(new WaitCallback(CheckIdle));
        }

        //To Start the File Distribution 
        private void startToolStripMenuItem_Click(object sender, EventArgs e)
        {
            startDistribution();
        }

        private void startDistribution()
        {
            startToolStripMenuItem.Enabled = false;
            stopToolStripMenuItem.Enabled = true;
            pauseToolStripMenuItem.Enabled = true;
            ResumeStripMenuItem1.Enabled = false;
            m_PauseByUser = false;
            Distribution.Distribution.ErrorTrace trace = new Distribution.Distribution.ErrorTrace(displayError);

            m_Go.Init(m_ConnectionString, trace);
        }

        //To Pause the File Distribution and Trigger the Asset Update Form for user to select the particular asset for udpated
        private void pauseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            pauseToolStripMenuItem.Enabled = false;
            ResumeStripMenuItem1.Enabled = true;
            m_PauseByUser = true;
            m_Go.Pause(); //Pause the File Distribution 
        }


        private void stopToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StopDistribution();
        }

        private void StopDistribution()
        {
            startToolStripMenuItem.Enabled = true;
            stopToolStripMenuItem.Enabled = false;
            pauseToolStripMenuItem.Enabled = false;
            ResumeStripMenuItem1.Enabled = false;
            m_PauseByUser = true;

            m_Go.CloseAll();
        }

        private void ResumeStripMenuItem1_Click(object sender, EventArgs e)
        {
            m_PauseByUser = false;
            ResumeStripMenuItem1.Enabled = false;
            pauseToolStripMenuItem.Enabled = true;
            m_Go.UnPause();
        }

        //Delegate Function for udpating the Asset list for the pop out window
        private void AssetListUpdate(string[] assetList)
        {
            foreach (string assetName in assetList)
            {
                string command = "sproc_ATC_Up_Mediainstance_Del_Update @AssetName ='"+ assetName + "'";
                UpdateDataBase(command);
            }
        }

        //The Deck Control command
        private void stopButton_Click(object sender, EventArgs e)
        {
            if (m_CamOb != null)
                m_CamOb.Dispose();
            m_ExtTransport.put_Mode(ExtTransportModes.Stop);
        }

        private void stepFF_Click(object sender, EventArgs e)
        {
            if(m_CamOb == null)
                m_CamOb = new ImageCapture.Capture(m_Dvc, deckPanel);

            m_ExtTransport.put_Mode(ExtTransportModes.StepFwd);
        }

        private void stepRew_Click(object sender, EventArgs e)
        {
            if (m_CamOb == null)
                m_CamOb = new ImageCapture.Capture(m_Dvc, deckPanel);

            m_ExtTransport.put_Mode(ExtTransportModes.StepRew);
        }

        private void playButton_Click(object sender, EventArgs e)
        {
            deviceReset();
            m_ExtTransport.put_Mode(ExtTransportModes.Play);
        }

        private void forwardButton_Click(object sender, EventArgs e)
        {
            m_ExtTransport.put_Mode(ExtTransportModes.FF);
        }

        private void rejectButton_Click(object sender, EventArgs e)
        {
            m_ExtTransport.put_MediaState(ExtTransportMediaStates.Unload);
        }

        private void renewButton_Click(object sender, EventArgs e)
        {
            m_ExtTransport.put_Mode(ExtTransportModes.Rew);
        }

        private void pauseButton_Click(object sender, EventArgs e)
        {
            m_ExtTransport.put_Mode(ExtTransportModes.Freeze);
        }

        //Reset the Panel after editing the advanced settings
        private void videoDeviceToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (m_CamOb != null)
                m_CamOb.Dispose();
            advancedSetup(m_DeviceOB);

            deviceReset();
        }

        //Reset the Panel after editing the advanced settings
        private void audioDeviceToolStripMenuItem_Click(object sender, EventArgs e)
        {
            object audioDeviceOB;

            if (m_CamOb != null)
                m_CamOb.Dispose();

            DsDevice audioDvc = DsDevice.GetDevicesOfCat(FilterCategory.AudioInputDevice)[1]; //initialize the dvc
            Guid iid = typeof(IBaseFilter).GUID;
            audioDvc.Mon.BindToObject(null, null, ref iid, out audioDeviceOB);

            advancedSetup(audioDeviceOB);

            deviceReset();

        }

        //Copy the Current DeckTime to the Start Capture Time input and calculate the End Capture Time based on the "Lenght" input
        private void setTimeBtn_Click(object sender, EventArgs e)
        {
            int frame, hour, min, sec;
            string sHour, sMin, sSec, sFrame;

            m_VidOb.BCDToFrameCount(out frame, out hour, out min, out sec, m_BCD);

            if (hour < 10)
                sHour = "0" + hour;
            else sHour = hour.ToString();
            if (min < 10)
                sMin = "0" + min;
            else sMin = min.ToString();

            if (sec < 10)
                sSec = "0" + sec;
            else sSec = sec.ToString();

            if (frame < 10)
                sFrame = "0" + frame;
            else sFrame = frame.ToString();

            startHour.Text = sHour;
            startMin.Text = sMin;
            startSec.Text = sSec;
            startFrame.Text = sFrame;

            CalculateEndPoint(hour, min, sec, sFrame);
        }

        //Initial attemp to Connect to the Deck

        private void CalculateEndPoint(int hour, int min, int sec, string sFrame)
        {
            string sHour, sMin, sSec;

            if (capLengthSec.Text != "" && Information.IsNumeric(capLengthSec.Text) && capLengthMin.Text != "" && Information.IsNumeric(capLengthMin.Text))
            {
                if (Convert.ToInt32(capLengthSec.Text) < 0 || Convert.ToInt32(capLengthMin.Text) < 0)
                    return;
                int secLenght = Convert.ToInt32(capLengthMin.Text)* 60 + Convert.ToInt32(capLengthSec.Text) + hour * 3600 + min * 60 + sec;
                TimeSpan tInterval = TimeSpan.FromSeconds(Convert.ToDouble(secLenght));

                if (tInterval.Hours < 10)
                    sHour = "0" + tInterval.Hours;
                else sHour = tInterval.Hours.ToString();
                if (tInterval.Minutes < 10)
                    sMin = "0" + tInterval.Minutes;
                else sMin = tInterval.Minutes.ToString();

                if (tInterval.Seconds < 10)
                    sSec = "0" + tInterval.Seconds;
                else sSec = tInterval.Seconds.ToString();

                endHour.Text = sHour;
                endMin.Text = sMin;
                endSec.Text = sSec;
                endFrame.Text = sFrame;
            }
            else
            {
                endHour.Text = "00";
                endMin.Text = "00";
                endSec.Text = "00";
                endFrame.Text = "00";
            }
        }

        //Send The Request of Switching the deck
        private void sRWDeckToolStripMenuItem_Click(object sender, EventArgs e)
        {
            m_LiveCapture = false;
            DeckButton(true);

            foreach (ToolStripMenuItem itemOB in captureInputSourceToolStripMenuItem.DropDownItems)
                itemOB.Checked = false;
            sRWDeckToolStripMenuItem.Checked = true;

            m_assetFtOb.SendRequest("Source01");

            m_assetFtOb.m_DeckResponse = "yellow";
        }

        /// <summary>
        /// J30 Deck input
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void j30DeckToolStripMenuItem_Click(object sender, EventArgs e)
        {
            m_LiveCapture = false;
            DeckButton(true);

            foreach (ToolStripMenuItem itemOB in captureInputSourceToolStripMenuItem.DropDownItems)
                itemOB.Checked = false;
            j30DeckToolStripMenuItem.Checked = true;

            m_assetFtOb.SendRequest("Source02");

            m_assetFtOb.m_DeckResponse = "yellow";
        }

        /// <summary>
        /// Router FeedA
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void routerFeedAToolStripMenuItem_Click(object sender, EventArgs e)
        {
            m_LiveCapture = true;
            deviceReset();
            DeckButton(false);

            foreach (ToolStripMenuItem itemOB in captureInputSourceToolStripMenuItem.DropDownItems)
                itemOB.Checked = false;
            routerFeedAToolStripMenuItem.Checked = true;

            m_assetFtOb.SendRequest("Source03");

            m_assetFtOb.m_DeckResponse = "yellow";
        }

        /// <summary>
        /// Router Feed B
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void routerFeedBToolStripMenuItem_Click(object sender, EventArgs e)
        {
            m_LiveCapture = true;
            deviceReset();
            DeckButton(false);

            foreach (ToolStripMenuItem itemOB in captureInputSourceToolStripMenuItem.DropDownItems)
                itemOB.Checked = false;
            routerFeedBToolStripMenuItem.Checked = true;

            m_assetFtOb.SendRequest("Source04");

            m_assetFtOb.m_DeckResponse = "yellow";
        }

        /// <summary>
        /// Cable TV1 feed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cableTV1ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            m_LiveCapture = true;
            deviceReset();
            DeckButton(false);

            foreach (ToolStripMenuItem itemOB in captureInputSourceToolStripMenuItem.DropDownItems)
                itemOB.Checked = false;
            cableTV1ToolStripMenuItem.Checked = true;

            m_assetFtOb.SendRequest("Source05");

            m_assetFtOb.m_DeckResponse = "yellow";
        }

        /// <summary>
        /// video input for the cable TV2
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cableTV2ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            m_LiveCapture = true;
            deviceReset();
            DeckButton(false);

            foreach (ToolStripMenuItem itemOB in captureInputSourceToolStripMenuItem.DropDownItems)
                itemOB.Checked = false;
            cableTV2ToolStripMenuItem.Checked = true;

            m_assetFtOb.SendRequest("Source06");

            m_assetFtOb.m_DeckResponse = "yellow";
        }

        /// <summary>
        /// menu click for the input 16 patchbay
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void input16patchbayToolStripMenuItem_Click(object sender, EventArgs e)
        {
            m_LiveCapture = true;
            deviceReset();
            DeckButton(false);

            foreach (ToolStripMenuItem itemOB in captureInputSourceToolStripMenuItem.DropDownItems)
                itemOB.Checked = false;
            input16patchbayToolStripMenuItem.Checked = true;

            m_assetFtOb.SendRequest("Source07");

            m_assetFtOb.m_DeckResponse = "yellow";
        }

        /// <summary>
        /// Disable or enable all the Control panel button
        /// </summary>
        /// <param name="work"></param>
        private void DeckButton(bool work)
        {
            renewButton.Enabled = work;
            playButton.Enabled = work;
            forwardButton.Enabled = work;
            stopButton.Enabled = work;
            rejectButton.Enabled = work;
            stepFF.Enabled = work;
            stepRew.Enabled = work;
            pauseButton.Enabled = work;
        }


        private void radioVideo_CheckedChanged(object sender, EventArgs e)
        {
            m_ImageSlide = false;
        }

        private void radioSlideShow_CheckedChanged(object sender, EventArgs e)
        {
            m_ImageSlide = true;
        }

        private void radioExistVideo_CheckedChanged(object sender, EventArgs e)
        {
            m_ImageSlide = false;
        }

        private void radioExistSlide_CheckedChanged(object sender, EventArgs e)
        {
            m_ImageSlide = true;
        }

        /// <summary>
        /// Listen to the action for changning Tab
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void assetTab_SelectedIndexChanged(object sender, EventArgs e)
        {
            m_ImageSlide = false;
            radioExistVideo.Checked = true;
            radioVideo.Checked = true;
        }

        /// <summary>
        /// Force the Application not to deinterlace programe
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void forceNoDeinterlaceSourceToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!m_ForceNotInterlace)
            {
                forceNoDeinterlaceSourceToolStripMenuItem.Checked = true;
                m_ForceNotInterlace = true;
            }
            else
            {
                forceNoDeinterlaceSourceToolStripMenuItem.Checked = false;
                m_ForceNotInterlace = false;
            }
        }

        /// <summary>
        /// Click to select the batch file
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_BatchFromFile_Click(object sender, EventArgs e)
        {
            m_OpenFileDialog1.InitialDirectory = "Z:\\";
            m_OpenFileDialog1.Filter = "All File (*.*)|*.*|QuickTime Movie (*.mov)|*.mov|Video Interleave (*.avi)|*.avi";
            m_OpenFileDialog1.FilterIndex = 1;
            m_OpenFileDialog1.RestoreDirectory = true;

            if (m_OpenFileDialog1.ShowDialog() == DialogResult.OK)
                TBox_BatchFile.Text = m_OpenFileDialog1.FileName;
        }
        
        /// <summary>
        /// Click to save the rename folder for image sequnces
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_BatchFromFolder_Click(object sender, EventArgs e)
        {
            if (m_FolderBrowserDialog1.ShowDialog() == DialogResult.OK)
                TBox_BatchFile.Text = m_FolderBrowserDialog1.SelectedPath;
        }

        /// <summary>
        /// Click to save the rename copy of video to be ingested in the background by autoingest
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_CreateBatch_Click(object sender, EventArgs e)
        {
            string fileName;
            string typeImageName;
            string outPutName="";

            if(radio_Batch_Video.Checked)
                typeImageName = "VID";
            else
                typeImageName = "PIC";

            if (channel_Batch.SelectedIndex == -1)
            {
                MessageBox.Show("Please Select Channel");
                return;
            }
            else if (channel_Batch.SelectedIndex == 0)
            {
                if (OutPut_Batch.SelectedIndex == 0)
                    outPutName = "M1";
                else if (OutPut_Batch.SelectedIndex == 1)
                    outPutName = "M2";
                else if (OutPut_Batch.SelectedIndex == 2)
                    outPutName = "M3";
                else if (OutPut_Batch.SelectedIndex == 3)
                    outPutName = "M4";
                else if (OutPut_Batch.SelectedIndex == 4)
                    outPutName = "M5";
            }
            else if (channel_Batch.SelectedIndex == 1)
            {
                if (playerBatch.SelectedIndex == 0)
                {
                    if (OutPut_Batch.SelectedIndex == 0)
                        outPutName = "RF2";
                    else
                        outPutName = "RF3";
                }
                else if (playerBatch.SelectedIndex == 1)
                {
                    if (OutPut_Batch.SelectedIndex == 0)
                        outPutName = "RL1";
                    else if (OutPut_Batch.SelectedIndex == 1)
                        outPutName = "RL2";
                    else if (OutPut_Batch.SelectedIndex == 2)
                        outPutName = "RL3";
                    else if (OutPut_Batch.SelectedIndex == 3)
                        outPutName = "RL4";
                    else if (OutPut_Batch.SelectedIndex == 4)
                        outPutName = "RL5";
                }
                else
                {
                    MessageBox.Show("Cannot Ingest into Ribbon Right Display");
                    return;
                }
            }
            else
               outPutName = "T3";

           string command = "select value from GlobalConfig where Property = 'FTPBatchIngestPath'";
           string ingestFolder = getDataObject(command).ToString();
           string batchFileName = "";

           if (File.Exists(TBox_BatchFile.Text))
           {
               FileInfo fName = new FileInfo(TBox_BatchFile.Text);
               string ext = fName.Extension.ToLower();

               if ((ext != ".avi") && (ext != ".mov"))
               {
                   MessageBox.Show("Plase select a AVI or MOV file");
                   return;
               }
               batchFileName = fName.Name.Replace(ext, "");
               if (batchFileName.Length > 40)
                   batchFileName = batchFileName.Remove(40);

               fileName = batchFileName + "_" + typeImageName + "_" + outPutName + "_-1" + fName.Extension;

               if (!Directory.Exists(ingestFolder))
                   Directory.CreateDirectory(ingestFolder);

               string[] fileCopy = { TBox_BatchFile.Text, ingestFolder + "\\" + fileName };

               ThreadPool.QueueUserWorkItem(new WaitCallback(m_assetFtOb.IngestFileCopy), (object)fileCopy);
           }
           else if(Directory.Exists(TBox_BatchFile.Text))
           {
               string[] batchFolderName = TBox_BatchFile.Text.Split('\\');

               batchFileName = batchFolderName[batchFolderName.Length - 1];
               if (batchFileName.Length > 40)
                   batchFileName = batchFileName.Remove(40);

               fileName = batchFileName + "_" + typeImageName + "_" + outPutName + "_-2";
               string[] folderCopy = { TBox_BatchFile.Text, ingestFolder + "\\" + fileName };

               ThreadPool.QueueUserWorkItem(new WaitCallback(m_assetFtOb.IngestFolderCopy), (object)folderCopy);
           }
        }

        /// <summary>
        /// Function of changing the disply Channel
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void channel_Batch_SelectedIndexChanged(object sender, EventArgs e)
        {
            List<string> playerIndexSet = new List<string>();

            if (channel_Batch.SelectedIndex != -1)
            {
                string getPlayersCountNN = "Select PlayersCountNN From Channel where ID =" + (channel_Batch.SelectedIndex + 1);
                int batchSlices = Convert.ToInt32(getDataObject(getPlayersCountNN));
                playerIndexSet.Add("Stretch To All");

                if (batchSlices > 1)
                {
                    // for (int i = 1; i <= m_TotalSlices; i++)
                    playerIndexSet.Add("Left Ribbon");
                    playerIndexSet.Add("Right Ribbon");
                }
            }
            else
                playerIndexSet.Add("Please Select Channel First");

            playerBatch.DataSource = playerIndexSet;
        }

        /// <summary>
        /// Function of changing the disply Channel
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void playerBatch_SelectedIndexChanged(object sender, EventArgs e)
        {
            DataSet ds = new DataSet();

            List<string> formatIndexSet = new List<string>();
            int defaultIndex = 0;

            if (channel_Batch.SelectedIndex == 0)
            {
                formatIndexSet = AddDisplayFormat(1, 0);
                defaultIndex = 1;
            }
            else if (channel_Batch.SelectedIndex == 1)
            {
                if (playerBatch.SelectedIndex == 1)
                {
                    m_TwoRibbonStrech = false;
                    formatIndexSet = AddDisplayFormat(2, 1);
                    defaultIndex = 2;
                }
                else if (playerBatch.SelectedIndex == 0)
                {
                    m_TwoRibbonStrech = true;
                    formatIndexSet = AddDisplayFormat(2, 0);
                    defaultIndex = 1;
                }
                else
                {
                    MessageBox.Show("No Right Ribbon Single output Avaible for Ingestion");
                    formatIndexSet = AddDisplayFormat(2, 0);
                    playerBatch.SelectedIndex = 0;
                    defaultIndex = 1;
                }
            }
            else if (channel_Batch.SelectedIndex == 2)
            {
                formatIndexSet.Add("ScaleWidth, Top Justify");
            }

            OutPut_Batch.DataSource = formatIndexSet;
            if (defaultIndex != 0)
                OutPut_Batch.SelectedIndex = defaultIndex;
        }

        /// <summary>
        /// Return the List of options that avaible according to the selected channel
        /// </summary>
        /// <param name="channelIndex"></param>
        /// <param name="playerIndex"></param>
        /// <returns></returns>
        private List<string> AddDisplayFormat(int channelIndex, int playerIndex)
        {
            List<string> formatIndexSet = new List<string>();

            if (channelIndex == 1)
            {
                formatIndexSet.Add("1) FullSize");
                formatIndexSet.Add("2) ScaleWidth,Center Vertical");
                formatIndexSet.Add("3) ScaleWidth,Top Justify");
                formatIndexSet.Add("4) ScaleHight,center Horizontal");
                formatIndexSet.Add("5) BestFit");
            }
            else if (channelIndex == 2 && playerIndex == 1)
            {
                formatIndexSet.Add("1) FullSize");
                formatIndexSet.Add("2) ScaleWidth,Center Vertical");
                formatIndexSet.Add("3) ScaleWidth,Top Justify");
                formatIndexSet.Add("4) ScaleHight,center Horizontal");
                formatIndexSet.Add("5) BestFit");
            }
            else if (channelIndex == 2 && playerIndex == 0)
            {
                formatIndexSet.Add("1) ScaleWidth,Center Vertical");
                formatIndexSet.Add("2) ScaleWidth,Top Justify");
            }

            return formatIndexSet;
        }

        /// <summary>
        /// Set the Capture's End point
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_SetEndTime_Click(object sender, EventArgs e)
        {
            CalculateEndPoint(Convert.ToInt32(startHour.Text), Convert.ToInt32(startMin.Text), Convert.ToInt32(startSec.Text), startFrame.Text);
        }

        private void logOutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Logout();
        }

        /// <summary>
        /// The listen fucntion for VideoSource changed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CoBox_VideoSoure_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (CoBox_VideoSoure.SelectedIndex != 0 && CoBox_VideoSoure.SelectedIndex != -1)
            {
                string caption = "Confirm With User";
                string message = "Warning: You have selected a Video Source that will not display the Iridas 3 / Ribbons Right player, \n but have selected stretching that will stretch some content to the Ribbons Right player. \n Are you sure you want to continue?";
                MessageBoxButtons buttons;
                DialogResult result;

                buttons = MessageBoxButtons.YesNo;

                result = MessageBox.Show(this, message, caption, buttons);
                if (result == DialogResult.No)
                    CoBox_VideoSoure.SelectedIndex = 0;
            }

        }

        /// <summary>
        /// Check if the input was in current format 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void capLength_TextChanged(object sender, EventArgs e)
        {
            if (!Information.IsNumeric(capLengthSec.Text) && capLengthSec.Text !="")
            {
                MessageBox.Show("Please key in Number in Second only");
                capLengthSec.Text = "";
            }
        }

        /// <summary>
        /// Refresh the list of Asset by Name
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_NewAssetSortByName_Click(object sender, EventArgs e)
        {
            string command = "Select ID, Name From Asset Where IsCombo = 'false' order by Name";

            SetAssetList(command);
        }

        /// <summary>
        /// Refresh the list of Asset by Date
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_NewAssetSortByDate_Click(object sender, EventArgs e)
        {
            string command = "Select ID, Name From Asset Where IsCombo = 'false' order by ID DESC";

            SetAssetList(command);
        }

        /// <summary>
        /// Refresh the List of Asset by Name
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_ExistingAssetSortByName_Click(object sender, EventArgs e)
        {
            string command = "Select ID, Name From Asset Where IsCombo = 'false' order by Name";

            SetAssetList(command);
        }

        /// <summary>
        /// Refresh the list of asset by Date
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_ExistingAssetSortByDate_Click(object sender, EventArgs e)
        {
            string command = "Select ID, Name From Asset Where IsCombo = 'false' order by ID DESC";

            SetAssetList(command);
        }

        /// <summary>
        /// Update the media in the Mediainstance table
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void updateAssetToolStripMenuItem_Click(object sender, EventArgs e)
        {
            assetUpdateForm.AssetUpDate listUpdate = new assetUpdateForm.AssetUpDate(AssetListUpdate); //Delegate call back function 
            DataSet ds = new DataSet();

            //Check for the availble list of Asset to update 
            string command = "sproc_ATC_AssetUpdateForm";
            ds = OpenConnection(command, "ASSETUPDATE");

            string[] assetList = new string[ds.Tables["ASSETUPDATE"].Rows.Count];
            int i = 0;
            foreach (DataRow drow in ds.Tables["ASSETUPDATE"].Rows)
                assetList[i++] = drow["Name"].ToString();

            assetUpdateForm assetUF = new assetUpdateForm(assetList, listUpdate);
            this.AddOwnedForm(assetUF);
            assetUF.Show();
        }

    }
}